使用 for 循环获取数据框的第 n 列

ace*_*01S 2 loops r dataframe

假设我有一个非常简单的数据框叫做sample

read.table(header=TRUE,text="a_1 a_2 a_3
                              1    1   1
                              1    1   1
                              1    1   1")
Run Code Online (Sandbox Code Playgroud)

我想通过使用 for 循环来获取此数据框的第 n 列。例如:

for(i in i:3) {
    nth <- sample$a_[i]
    #there are still a lot more lines of code after this, think a bajillion calculations
}
Run Code Online (Sandbox Code Playgroud)

显然这行不通(我认为 Java 真的很难)。R中的任何等价物?

这是来自 R 新手程序员的新手问题。

感谢任何回复的人。

编辑 这只是所讨论情况的最简单形式。我拥有的真实数据框非常广泛。

Ist*_*rel 5

您可以使用data_frame[, "column_name"]表示法按名称访问列。对于您的示例,它将如下所示:

col_names <- colnames(sample)
for(i in c(1:3)) {
   nth <- sample[, col_names[i]]
   print(nth)
}
Run Code Online (Sandbox Code Playgroud)

它给

[1] 1 1 1
[1] 1 1 1
[1] 1 1 1
Run Code Online (Sandbox Code Playgroud)

对于更复杂的情况,您可以使用eval函数来评估字符串中的命令。在这里,您可能需要sprintf函数来准备该字符串。例如:

for(i in c(1:3)) {
    # prepare call string
    name_call <- sprintf("sample$a_%s", i)
    # evaluate command from string
    nth <- eval(parse(text = name_call))
    print(nth)
}
Run Code Online (Sandbox Code Playgroud)

它再次给出:

[1] 1 1 1
[1] 1 1 1
[1] 1 1 1
Run Code Online (Sandbox Code Playgroud)