简体   繁体   中英

How to assign values in new column based on condition in another column using if and non-if functions in R

I have a data set "data". If the variable (in long form) contains A1 or D1, assign "1:5 dil" in data$dilutions column. If it has B1 or C1 assign "1:10 dil". How can I do this using both if and non-if functions?

In the original data I have lots of assignments, hence I want to see if non-if conditions work better

cycles <- c(1:100)
A1 <- c(1:100)
B1 <- c(100:199)
C1 <- c(5:104)
D1 <- c(0:99)
data <- data.frame("cycles" = cycles, "A1" = A1, "B1" = B1, "C1" = C1, "D1" = D1)


library(reshape2)
data <- melt(data, id.vars=c("cycles"))
data$dilutions <- if(data$variable=="A1"|"D1" <- "1:5 dil", data$variable== "B1" | "C1" <- "1:10 dil")

As mentioned in the comments, your use of the if statement is incorrect. Here are two approaches, one making use of ifelse() and one using direct assignments on subsets.

data$dilutions <- ifelse(data$variable == "A1" | data$variable == "D1", "1:5 dil", "1:10 dil")

If you have more than these two possible outcomes, you may need to chain your ifelse statements (ie, use another ifelse() for the else part of the call.

Otherwise, you can use direct assignments, like so:

data$dilutions[data$variable=="A1" | data$variable== "D1"] <- "1:5 dil"
data$dilutions[data$variable=="B1" | data$variable== "C1"] <- "1:10 dil"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM