How to access the name of a column which is a number through a variable

时间:2019-03-19 14:45:56

标签: r dataframe

Problem : I can't select the column of a dataframe through a variable if the column is a number. Example:

library(dplyr)
df = data.frame(a=c(1,2,3),b=c(4,5,6)) #Create a dataframe

colnames(df) <- c("99","66") #Column names are numbers (let's say the id of something)

I can do this:

print(df$`99`[1])

But I can't do this:

k <- 99
print(df$`k`[1])

The reason I'm trying to use a variable to access the column name is that I want to loop over the column names:

for (i in colnames(df)){
  df$"i"
  df[,i]
}

1 个答案:

答案 0 :(得分:0)

您可以简单地做-

> k=99
> df[[paste0(k)]]
[1] 1 2 3

只是为了进一步说明您的for loop-

cols <- c(99,66)
for(i in 1:length(cols))
{
   print(df[[paste0(cols[i])]])
}

输出-

[1] 1 2 3
[1] 4 5 6