我正在尝试基于列表(fish_species)循环命令。虽然我发现了很多例子,但我还没有找到一个也包括将列名更改为循环的一部分。我已经弄清楚如何获得单个物种的预期结果(第10-13行),但在实际数据集中我有~500种,我宁愿不重复此命令500次以上。有没有办法替换列表中的变量值?
Fishdata$variable <- ifelse(fishdata$Species== “variable”,fishdata$Number,0)
我知道如何做到这一点是ArcGIS,但我正在努力扩大我的视野并学习R.这也是我的第一篇文章,所以请原谅任何搞砸。 感谢您提供任何帮助。
fishdata <-c()
fishdata$Site <-c(1,1,1,2,2,2)
fishdata$Species <- c("one_fish", "two_fish", "two_fish", "red_fish", "blue_fish", "blue_fish")
fishdata$Number <- c(1,1,1,1,1,1)
fishdata$one_fish <-0
fishdata$two_fish <-0
fishdata$red_fish <-0
fishdata$blue_fish <-0
fish_list <- c("one_fish","two_fish", "red_fish", "blue_fish")
fishdata$one_fish <- ifelse(fishdata$Species=="one_fish",fishdata$Number,0)
fishdata$two_fish <- ifelse(fishdata$Species=="two_fish",fishdata$Number,0)
fishdata$red_fish <- ifelse(fishdata$Species=="red_fish",fishdata$Number,0)
fishdata$blue_fish <- ifelse(fishdata$Species=="blue_fish",fishdata$Number,0)
答案 0 :(得分:2)
您可以使用sapply
来迭代物种,
sapply(fishdata$Species, function(i)ifelse(fishdata$Species== i, fishdata$Number,0))
# one_fish two_fish two_fish red_fish blue_fish blue_fish
#[1,] 1 0 0 0 0 0
#[2,] 0 1 1 0 0 0
#[3,] 0 1 1 0 0 0
#[4,] 0 0 0 1 0 0
#[5,] 0 0 0 0 1 1
#[6,] 0 0 0 0 1 1
答案 1 :(得分:0)
$
只是[]
运算符的替代选择:
a$x
a["x"]
所以你可以这样做:
fishdata[species] <- ifelse(fishdata$Species == species, fishdata$Number, 0)
for (species in fish_species) {
fishdata[species] <- ifelse(fishdata$Species == species, fishdata$Number, 0)
}