lundi 11 janvier 2021

Replace column values based on row criteria

Trying to replace specific column values with NA based on specific row criteria in a data frame. Example dataset (test) and the code I have tried are below. Note that my actual dataset is much larger but I essentially need to replace specific columns in specific rows (certain years) with NA. In the example I'm trying to use column indexing to insert NAs for columns 3:5 for year 2002, but the result ends up replacing all values in columns 3:5 with NAs. I do want to use column indexing instead of column names because I have many columns in my actual data.

test <- data.frame(YEAR=c(2000,2001,2002,2003,2004,2000,2001,2002,2003,2004),
    zone=c('A','A','A','A','A','B','B','B','B','B'),
    value=c(5,9,2,5,7,1,8,4,2,1),
    value2=c(5,3,6,8,9,7,2,6,1,7),
    value3=c(1,5,7,3,9,1,8,2,9,8))

ifelse(test$YEAR==2002,test[,3:5]<-NA,test[])

Aucun commentaire:

Enregistrer un commentaire