Vasile Vasile - 1 month ago 8
R Question

Make NA observations that are identical with observations in adjacent column

My data frame:

structure(list(make = c("land rover", "land rover", "land rover",
"land rover", "land rover", "land rover", "land rover", "land rover",
"land rover", "land rover"), model = c("freelander", "range",
"discovery", "freelander", "range", "discovery", "discovery",
"range", "discovery", "range"), body = c("freelander", "sport",
"discovery", "2", "evoque", "sport", "4x4", "range", "4", "sport"
)), .Names = c("make", "model", "body"), row.names = c(92L, 178L,
185L, 192L, 202L, 224L, 233L, 448L, 473L, 480L), class = "data.frame")


I would like to NA those observations in column 'body' that are identical to observations in column 'model'. In this case this would be rows 1,3,8.
I tried the following function which does not give any errors, but also does not produce any results:

RemovingNames <- function(df){
for(i in 1:nrow(df))
ifelse(identical (df[i,2], df[i,3]), df[i,3]<-NA, df[i,3]<-df[i,3])
}

ira ira
Answer

If you call your dataset "test", then:

test[test[,"model"] == test[, "body"], "body"] <- NA