我对R世界很陌生 我试图从数据框的每一列自动创建一个向量,该向量的名称是此列标题的名称,并在需要时调用它。
对于示例,我将使用" mtcars" Rtutorial提供的数据框
# use mtcars dataframe and reduce it for this example purpose
a=mtcars
a=mtcars[1:3,2:5]
# Store Column Names in a vector
col=colnames(a)
# use a for loop from 1 to Number of columns to create vectors that:
# 1. store column values and
# 2. named as column header
for (i in 1:length(col)) {
assign(col[i],as.character(a[,i]))
}
#(So Far So Good),
# Let'z try to do a simple print of all vector created by the for loop
for (i in 1:length(col)) {
print(col[i])
}
这是我的问题:
这个第二个循环打印矢量col [i]的值 所以基本上每次迭代我都会得到
但我想要获得的不是 col 向量的[ i ]值。 我想要的是向量中包含的值,称为 col [i] 所以在第二次循环之后,我会撒谎来获得:
答案 0 :(得分:2)
您需要的是get
。
for (i in 1:length(col)) {
print(get(col[i]))
}
没有它,您将打印向量col
的值,而不是存储在名称为变量的变量中。
答案 1 :(得分:1)
使用for (i in 1:length(col)) {
print(get(col[i]))
}
#[1] "6" "6" "4"
#[1] "160" "160" "108"
#[1] "110" "110" "93"
#[1] "3.9" "3.9" "3.85"
功能。
struts.xml