Using if else on a dataframe across multiple columns

后端 未结 6 1367
情书的邮戳
情书的邮戳 2021-01-14 21:43

I have a large dataset of samples with descriptors of whether the sample is viable - it looks (kind of) like this, where \'desc\' is the description column and \'blank\' ind

6条回答
  •  遥遥无期
    2021-01-14 22:34

    For your example dataset this will work;

    Option 1, name the columns to change:

    dat[which(dat$desc == "blank"), c("x", "y", "z")] <- NA
    

    In your actual data with 40 columns, if you just want to set the last 39 columns to NA, then the following may be simpler than naming each of the columns to change;

    Option 2, select columns using a range:

    dat[which(dat$desc == "blank"), 2:40] <- NA
    

    Option 3, exclude the 1st column:

    dat[which(dat$desc == "blank"), -1] <- NA
    

    Option 4, exclude a named column:

    dat[which(dat$desc == "blank"), !names(dat) %in% "desc"] <- NA
    

    As you can see, there are many ways to do this kind of operation (this is far from a complete list), and understanding how each of these options works will help you to get a better understanding of the language.

提交回复
热议问题