如何从R中for循环的迭代结果中获得向量?

如何从R中for循环的迭代结果中获得向量?,r,dataframe,loops,iteration,R,Dataframe,Loops,Iteration,我有这个数据帧(df),当“ID”列与给定向量(idvector)的值匹配时,我需要得到列“amountN”中的值的向量,所以我创建了一个for循环,我通过打印df$amountN的值来测试它,以检查它们是否真的完成了df$ID条件,它们确实完成了。这是for循环: df amountS amountN ID 64693 0.440 0.55 028 64702 0.360 0.52 028 64708 0.220 0.33 028 64714 0

我有这个数据帧(df),当“ID”列与给定向量(idvector)的值匹配时,我需要得到列“amountN”中的值的向量,所以我创建了一个for循环,我通过打印df$amountN的值来测试它,以检查它们是否真的完成了df$ID条件,它们确实完成了。这是for循环:

df
      amountS amountN  ID
64693   0.440    0.55 028
64702   0.360    0.52 028
64708   0.220    0.33 028
64714   0.500    0.27 028
64720   0.280    0.51 028
64726   0.520    0.47 028
64732   0.410    0.25 028
64735   0.090    0.11 028
64741   0.220    0.17 028
64750   0.630    0.48 028
64756   0.430    0.35 028
64762   1.200    0.40 028
65150   4.425   14.95 029
65156   5.035   23.60 029
65163   5.810   26.20 029

idvector <- c("010","025","028")

for(i in seq_len(nrow(df))){
    for (j in seq_len(length(idvector))){
      if(df$ID[i] == idvector[j]){
        print(df$amountN[i])
      }
    }
  }
我查看了数据,发现这些值如下所示:

[1] 0.55
[1] 0.52
[1] 0.33
[1] 0.27
[1] 0.51
[1] 0.47
[1] 0.25
[1] 0.11
[1] 0.17
[1] 0.48
[1] 0.35
[1] 0.4
 [1]  0.55  0.52  0.33  0.27  0.51  0.47  0.25  0.11  0.17  0.48 
[11]  0.35  0.40
它们应该是这样的:

[1] 0.55
[1] 0.52
[1] 0.33
[1] 0.27
[1] 0.51
[1] 0.47
[1] 0.25
[1] 0.11
[1] 0.17
[1] 0.48
[1] 0.35
[1] 0.4
 [1]  0.55  0.52  0.33  0.27  0.51  0.47  0.25  0.11  0.17  0.48 
[11]  0.35  0.40
我真的需要一个向量或子集,这样我就可以对数据应用汇总统计数据和其他数据,但还没有弄清楚


我在
基本R
中使用了R版本4.0.3

,使用
子集

subset(df, ID %in% idvector, select = amountN)$amountN
#[1] 0.55 0.52 0.33 0.27 0.51 0.47 0.25 0.11 0.17 0.48 0.35 0.40

关于OP的代码,我们可以将“x”定义为
NULL
向量,然后在每个循环中串联“x”,并将其分配回“x”。此外,请确保“idvector”的类型相同,即假设它也是数字

x <- c()
for(i in seq_len(nrow(df))){
    for (j in seq_len(length(idvector))){
      if(df$ID[i] == idvector[j]){
        x <- c(x, df$amountN[i])
      }
      x
    }
  }
注意:OP代码中的问题是“x”在每次迭代中都会得到更新,同时删除以前的输出。它需要连接

数据
df在
baser
中,使用
子集

subset(df, ID %in% idvector, select = amountN)$amountN
#[1] 0.55 0.52 0.33 0.27 0.51 0.47 0.25 0.11 0.17 0.48 0.35 0.40

关于OP的代码,我们可以将“x”定义为
NULL
向量,然后在每个循环中串联“x”,并将其分配回“x”。此外,请确保“idvector”的类型相同,即假设它也是数字

x <- c()
for(i in seq_len(nrow(df))){
    for (j in seq_len(length(idvector))){
      if(df$ID[i] == idvector[j]){
        x <- c(x, df$amountN[i])
      }
      x
    }
  }
注意:OP代码中的问题是“x”在每次迭代中都会得到更新,同时删除以前的输出。它需要连接

数据
df您可以使用
df
和索引中的
%in%
直接避免循环ans:

#Code
vec <- df$amountN[df$ID %in% idvector]

您可以使用%
中的
%直接避免循环ans,而不是
df
和索引:

#Code
vec <- df$amountN[df$ID %in% idvector]

谢谢!我实际上在用你的,但我是新来的!工作得很好,非常感谢!我实际上在用你的,但我是新来的!工作得很好