'Changing a value to N/A

I did a questionnaire research where some of the answers were "I don't know" and "I don't want to answer". Now I need to change those answering options to "N/A" so that they won't be accounted for in my statistical analyses. How do I do this?

rna


Solution 1:[1]

That is pretty easy to accomplish. I am making some assumptions about your data, since you didn't provide the format. Let's assume that you have your data in an excel spreadsheet and you have imported it into R with the following code:

## Import Data ##
require("gdata")
myData <-read.xls("myData.xlsx", stringsAsFactors = FALSE)

Ok, now you have a data frame in R called myData. Let's assume that there is a column called Answers which contains the responses as strings. We have some good responses, some NA values, and some that say "I don't know" or "I don't want to answer" or similar.

This code will change any answers that start with "I don't" to NA.

myData$Answers[startsWith(myData$Answers,"I don't")] <- NA

Or you could specify each NA answer individually
(such as if there are some good answers that start with "I don't").

myData$Answers[myData$Answers == "I don't know")] <- NA
myData$Answers[myData$Answers == "I don't want to answer")] <- NA

Or you can change all answers that contain a specific phrase anywhere in their answer to NA

myData$Answers[grepl("don't know", myData$Answers)] <- NA

If you imported strings as factors then the code above would change like this:

myData$Answers[grepl("don't know", levels(myData$Answers))] <- NA

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 enpitsu