【发布时间】:2016-08-17 22:03:56
【问题描述】:
我遇到了嵌套 for 循环和 ifelse 语句的问题。这是我的数据框abund:
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 中的物种相匹配,则将列C2 到C4 一起添加到一个新向量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
感谢您的宝贵时间和帮助。
【问题讨论】:
标签: r if-statement for-loop