R: Using Apply Function to clean likert answers

人走茶凉 提交于 2019-12-24 15:32:43

问题


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


回答1:


Try

apply(df[,18:134], 2, function(x) gsub("[^0-9]", "", x))


来源:https://stackoverflow.com/questions/35819788/r-using-apply-function-to-clean-likert-answers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!