r - 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")
解决方案
如评论中所述,您对该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"
推荐阅读
- ios - Swift Json 值不断出现“nil”
- php - 教义-namedQuery 执行的内存泄漏?
- java - JavaFX - 图片网址未加载
- python - 将值累积到字典中的相应键?
- php - Laravel 中一个控制器的两个模型(方法编辑和更新)
- typescript - 无法读取未定义 Ionic 3 的属性获取
- python - 在 Python(Pandas) 中清理模糊重复和行的标准化
- android - 问题:为什么react native video不全屏播放视频?
- angular - 错误:必须为具有名称的表单控件提供值:
- scala - rdd 与数据帧 Spark 上的序列化