Reputation: 972
Sample of the data I am working with below. I already omitted all rows with a "NA" in them.
gss.s[1:5,]
abany advfront arrest
2 YES Agree NO
3 YES Strongly agree YES
10 YES Agree YES
16 YES Agree NO
21 NO Strongly agree NO
I am trying to replace the "YES" with a 1 in the abany column and "NO" with -1 in abany column. I tried using replace replace(gss.s[,1], "YES", 1) but got the error Invalid Factor Level, NA generated. I read a previous post about this same problem and couldn't figure out how to apply the solution to my problem.
Upvotes: 1
Views: 8537
Reputation: 99331
You could use ifelse()
on the column, changing all values at once.
gss.s$abany <- ifelse(gss.s$abany == "YES", 1, -1)
gss.s
## abany advfront arrest
## 2 1 Agree NO
## 3 1 Strongly agree YES
## 10 1 Agree YES
## 16 1 Agree NO
## 21 -1 Strongly agree NO
Upvotes: 2
Reputation: 6197
You can also create a vector in which you define the changes you would like to make. It is a lot quicker if you have big datasets compared to ifelse
statements.
translate <- c(YES=1,NO=-1)
gss.s$abany2 <- translate[as.character(gss.s$abany)]
gss.s
# abany advfront arrest abany2
# 1 YES Agree NO 1
# 2 YES Strongly agree YES 1
# 3 YES Agree YES 1
# 4 YES Agree NO 1
# 5 NO Strongly agree NO -1
You also don't have to struggle with nested ifelse
functions if you have multiple changes to make:
translate2 <- c('Strongly agree'=2,Agree=1,Disagree=-1,'Strongly disagree'=-2 )
gss.s$advfront2 <- translate2[as.character(gss.s$advfront)]
gss.s
# abany advfront arrest abany2 advfront2
# 1 YES Agree NO 1 1
# 2 YES Strongly agree YES 1 2
# 3 YES Agree YES 1 1
# 4 YES Agree NO 1 1
# 5 NO Strongly agree NO -1 2
Upvotes: 0
Reputation: 2030
y <- data.frame ("abany"=c("YES","YES","YES","YES","NO"),
"advfront"=c("Agree","Strongly Agree","Agree","Agree","Strongly Agree"),
"arrest"=c("NO","YES","YES","NO","NO"))
I would try another way: Convert factor column to character
y$abany <- as.character.factor (y$abany)
So now you don't have any problem to change values of the column
y[y$abany=="YES", "abany"] <- 1
y[y$abany=="NO", "abany"] <- -1
Upvotes: 2