我遇到嵌套for循环和ifelse语句的问题。这是我的数据框abund
:r - 如何用for循环和ifelse创建矢量
Species Total C1 C2 C3 C4
1 Blue 223 73 30 70 50
2 Black 221 17 50 56 98
3 Yellow 227 29 99 74 25
4 Green 236 41 97 68 30
5 Red 224 82 55 21 66
6 Orange 284 69 48 73 94
7 Black 154 9 63 20 62
8 Red 171 70 58 13 30
9 Blue 177 57 27 8 85
10 Orange 197 88 61 18 30
11 Orange 112 60 8 31 13
我想补充一些共同abund
的列,但只有当他们符合我的矢量colors
指定了正确的物种。
colors <- c("Black", "Red", "Blue")
所以,如果在abund
的Species
在color
物种匹配,则通过C4
添加列C2
起来的一种新型载体minus
。如果abund
中的物种与color
中的物种不匹配,则将新0添加到新载体minus
。
我遇到了我的代码问题,希望它只是定义一个范围的小问题,但我不确定。这是到目前为止我的代码:
# Use for loop to create vector of sums for select species or 0 for species not selected
for(i in abund$Species)
{
for(j in colors)
{
minus <- ifelse(i == j, sum(abund[abund$Species == i,
"C2"]:abund[abund$Species == i, "C4"]), 0)
}
}
它返回这样的:There were 12 warnings (use warnings() to see them)
而这个 “载体”:minus
[1] 0
这是我的目标:
minus
[1] 150 204 0 0 142 0 145 101 120 0 0
谢谢您的时间,帮助这一点。
好又直爽! – Gregor
你也可以乘以用于'inColors'的逻辑向量 - '%abund * Species%in%colors * rowSums(abund [c(“C2”,“C3”,“C4”)])' – thelatemail
非常感谢很多,@巴克!这就像一个冠军。你的解释值得很多,并澄清了我对循环的许多误解。再次感谢。 – Metridia