首页 > 解决方案 > 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")

标签: rif-statementvariable-assignment

解决方案


如评论中所述,您对该if语句的使用不正确。这里有两种方法,一种使用ifelse()子集,另一种使用子集上的直接分配。

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

如果您有超过这两个可能的结果,您可能需要链接您的ifelse语句(即,在调用部分使用另一个ifelse()语句else

否则,您可以使用直接分配,如下所示:

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

推荐阅读