Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ifelse to replace values in a column

Tags:

r

I have a column in my dataframe as follows:

Private
Private
Private
 ?
Private

I want to replace this " ?" with Private. I have a solution as follows:

# Only replacing ? with Private 
df$var <- ifelse(df$var == " ?", " Private", df$var)

However when I print out the df$var column after the ifelse statement, these values don't seem correct. This is what I got:

3
3
3
Private
3

I don't know what went wrong here.

like image 707
Zack Avatar asked Sep 20 '15 19:09

Zack


3 Answers

This should work, using the working example:

var <- c("Private", "Private", "?", "Private")
df <- data.frame(var)
df$var[which(df$var == "?")] = "Private"

Then this will replace the values of "?" with "Private"

The reason your replacement isn't working (I think) is as if the value in df$var isn't "?" then it replaces the element of the vector with the whole df$var column, not just reinserting the element you want.

like image 163
JCollerton Avatar answered Oct 03 '22 01:10

JCollerton


It looks like the ifelse alternative replacement is returning an integer that could be interpreted as a level ... try

df$var <- ifelse(df$var == " ?", " Private", as.character(df$var))   
like image 20
Markm0705 Avatar answered Oct 03 '22 01:10

Markm0705


JCollerton's solution should work well, but if you insist using if statment, you will have to do it in a for loop:

for(i in 1:nrow(df)){
    if(df$var[i]==" ?"){
        df$var[i]="Private"
     }
}
like image 41
Ting Avatar answered Oct 03 '22 00:10

Ting