R ifelse to replace values in a column

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.


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))   

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"
     }
}