R: Using Apply Function to clean likert answers

2019-08-09 08:51发布

I have a survey where users have filled in answers to questions on a likert scale. The software we are using has put text into the answers when all i want is numbers so an example is NEITHER AGREE NOR DISAGREE4. I want to convert it to 4

I have R code that does this where it looks for a number in the cell of the dataframe for column 18 and extracts the number from it if it exists

as.numeric(ifelse(grepl("[0-9]",df[,18]),as.numeric(gsub(x = df[,18],"[A-z]","")), df[,18]))

I would like to be able to do this for cols 18:134

I can do this with a for loop, i guess but i think this is a perfect example of how to use one of the apply functions and i would like to learn.

Thanks

标签: r apply
1条回答
不美不萌又怎样
2楼-- · 2019-08-09 09:23

Try

apply(df[,18:134], 2, function(x) gsub("[^0-9]", "", x))
查看更多
登录 后发表回答