首页 > 解决方案 > 迭代数据帧并在 R 中生成向量

问题描述

我有一个包含 12 列的数据框。基本上,我正在尝试做一个 for 循环,它将遍历每一列并将每一列存储为它自己的向量。我希望能够将每个向量用作另一个包的输入。

for (i in 1:ncol(df)) {
  #extract each column from left to right one by one
  
  #store each of these columns in their own vector

标签: rdataframeloopsiteration

解决方案


正如评论中所指出的,数据框已经是一个向量列表。您可以使用双括号语法访问向量。因此,您不需要将它们存储在新变量中。像这样:

# Subset iris data frame for illustration purposes
df <- iris[1:5, ]

# Create sample function to print out class and vector values
myfunction <- function(vct) {
  
  print(class(vct)) 
  print(vct)
}

# Iterate columns and pass to function
for (i in 1:ncol(df)) {
  
   myfunction(df[[i]])
  
}

# Results
# [1] "numeric"
# [1] 5.1 4.9 4.7 4.6 5.0
# [1] "numeric"
# [1] 3.5 3.0 3.2 3.1 3.6
# [1] "numeric"
# [1] 1.4 1.4 1.3 1.5 1.4
# [1] "numeric"
# [1] 0.2 0.2 0.2 0.2 0.2
# [1] "factor"
# [1] setosa setosa setosa setosa setosa
# Levels: setosa versicolor virginica



推荐阅读