如何根据R中的条件添加列 [英] how can i add a column based on condition in R
本文介绍了如何根据R中的条件添加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有像这样的df(data1)
i have df(data1) like this
internode_length treatment genotype
1 98.165 sun B3
2 116.633 sun B3
3 103.474 sun B3
4 120.683 sun B3
5 109.128 sun B3
6 129.076 sun B3
我想根据条件为此df添加一个单独的列
And i want to add a separate column to this df based on condition
for i in (1:nrow(data1)){
if (data1$genotype == "B3") {
data1$mutation = "wt"
} else if (data1$genotype == "ein9" & "ein194"){
data1$mutation = "phyB"
} else {
data1$mutation = "hy2"
}
}
但是我收到此错误并发出警告并且无法正常工作
But i am getting this error and warning and also it does not work
Error: unexpected symbol in "for i"
> if (data1$genotype == "B3") {
+ data1$mutation = "wt"
+ } else if (data1$genotype == "ein9"){
+ data1$mutation = "phyB"
+ } else {
+ data1$mutation = "hy2"
+ }
Warning message:
In if (data1$genotype == "B3") { :
the condition has length > 1 and only the first element will be used
> }
Error: unexpected '}' in "}"
有什么建议可以解决这个问题吗?
Any suggestions to fix this?
推荐答案
你应该使用 ifelse
:
transform(data1,
mutation = ifelse (genotype == "B3", "wt",
ifelse (genotype %in% c("ein9","ein194"),
"phyB", "hy2")))
# internode_length treatment genotype mutation
# 1 98.165 sun B3 wt
# 2 116.633 sun B3 wt
# 3 103.474 sun ein9 phyB
# 4 120.683 sun B3 wt
# 5 109.128 sun ein194 phyB
# 6 129.076 sun A2 hy2
这篇关于如何根据R中的条件添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文