如何将循环输出转换为向量?

时间:2019-05-22 12:23:28

标签: r

我使用循环函数从数据集Z中提取某些值(位置在数据集A中给出)。

#Exemplary datasets
Z <- data.frame(Depth=c(0.02,0.04,0.06,0.08,0.10,0.12,0.14,0.16,0.18,0.2), 
Value=c(10,12,5,6,7,4,3,2,11,13))
A <- data.frame(Depth=c(0.067, 0.155))

for (n in c(1:nrow(A)))
+ {find_values <- Z$Value[Z$Depth>=A$Depth[n]][1]
+ print(find_values)}

#Result
[1] 6
[1] 2

结果似乎由两个单独向量中的值组成。如何将它们轻松合并为一个向量,如下所示?

[1] 6, 2

谢谢!

2 个答案:

答案 0 :(得分:1)

要使代码按原样工作,您可以在for循环中使用索引存储它们

for (n in seq_len(nrow(A))) {
   find_values[n] <- Z$Value[Z$Depth>=A$Depth[n]][1]
}
find_values
#[1] 6 2

不过,您可以使用sapply来简化此操作

sapply(A$Depth, function(x) Z$Value[which.max(Z$Depth >= x)])
#[1] 6 2

答案 1 :(得分:0)

我们可以使用向量化方法

Z$Value[findInterval(A$Depth, Z$Depth) + 1]
#[1] 6 2