r - 迭代数据帧并在 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
解决方案
正如评论中所指出的,数据框已经是一个向量列表。您可以使用双括号语法访问向量。因此,您不需要将它们存储在新变量中。像这样:
# 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
推荐阅读
- android - 如何正确地将数据从 Android 发送到 Flutter?
- vue.js - 调用 Vuex 突变需要太多时间来加载内容和突变
- c++ - 逻辑运算符 || 和 && 的区别 - 我一直在犯错误
- javascript - 协助展平包含一个对象(或可能超过 1 个)的对象数组
- ffmpeg - ffmpeg - 一次执行 2 个或更多命令
- node.js - 如何捆绑环境依赖包?
- matplotlib - 记录互动情节
- regex - Atom.io 搜索字段中的正则表达式
- javascript - Napi::ObjectWrap: 是一个析构函数,如何调用?
- python - 如何将一个 numpy 元组数组解压缩到一个 ndarray 中?