for循环使用条件if语句

时间:2017-11-16 01:59:11

标签: r for-loop if-statement

我无法弄清楚这段代码有什么问题。我有一个名为Fish的数据框。我想添加一个名为CombineMe的列,默认为0.如果满足两个条件,则值将更改为501(数据源= A& sample method = visual,那么它将等于501,如果数据源= B& taxon代码是三个EJ,EL或RV)。我无法弄清楚我哪里出错了。我已经尝试调整[i]的位置并添加逗号......

for(i in 1:length(Fish)) {
Fish$CombineMe <- 0 
if (Fish$data_source == "A" & Fish$sample_method == "visual") {
  Fish$CombineMe [i] <- 501
} else if (Fish$data_source == "B" & Fish$taxon_name == c("EJ", "EL", "RV")){
  Fish$CombineMe [i] <- 501
}}

这是鱼的样子的简明例子:

Fish <- data.frame ("data_source"=c("A", "A", "B", "C", "C", "D", "D"), "sample_method"= c("visualfish", "fish", "fish", "fish", "fish", "fish", "fish"), 
                  "taxon_name"=c("EJ", "EJ", "RV", "EJ", "RV", "EL", "HR"))

3 个答案:

答案 0 :(得分:1)

通常,您需要提供Fish数据帧的外观。我试着根据你给出的代码猜测:

Fish$CombineMe <- 0 
for(i in 1:nrow(Fish)) {

if (Fish$data_source[i] == "A" & Fish$sample_method[i] == "visual") {
  Fish$CombineMe[i] <- 501
} else if (Fish$data_source[i] == "B" & Fish$taxon_name[i] %in% c("EJ", "EL", "RV")){
  Fish$CombineMe [i] <- 501
}}

但我认为你不需要循环。以下是使用ifelse的替代方法。

Fish$CombineMe <- 0
Fish$CombineMe <- ifelse(Fish$data_source == "A" & Fish$sample_method == "visual", 501, Fish$CombineMe)
Fish$CombineMe <- ifelse(Fish$data_source == "B" & Fish$taxon_name %in% c("EJ", "EL", "RV"), 501, Fish$CombineMe)

答案 1 :(得分:1)

这是令人讨厌的代码行:

Fish$CombineMe <- 0

对于循环的每次迭代,您将整个列归零。将它移到外面和循环之前它应该可以工作。

但是R是一种矢量化语言,更好的制作方法甚至根本不使用循环:

cond1 <- Fish$data_source == 'A' & Fish$sample_method == 'visual'
cond2 <- Fish$data_source == "B" & Fish$taxon_name %in% c('EJ', 'EL', 'RV')
Fish$CombineMe <- ifelse(cond1 | cond2, 501, 0)

答案 2 :(得分:0)

您遇到的问题是因为每次循环时都定义Fish$CombineMe <- 0,因此您每次都要将孔列重新设置为cero。解决这个问题:

Fish$CombineMe[i] <- 0