简体   繁体   中英

Getting column names from df and querying df

When I do:

var = names(df)[2]

df$var

I get NULL . I think that var is a string inside quotes and that is why this is happening. How could get the columns in a dataframe and dynamically query them?

It has been suggested that I use df[var], but what if my dataframe has another dataframe within it? df[var][x] or df[var]$x won't work.

通过执行以下操作,通过变量的值获取数据框或列表中项目的列:

df[[var]]

It's hard to know what error-inducing situation has been constructed without dput-output on the offending dataframe. It's modestly difficult to get a column name as described (with actual quotes in the column name, but its possible. First we can try and fail to get such a beast:

df2 <- data.frame("\"col1\""=1:10)
df2[["\"col1\""]]
#NULL
df2
#    the data.frame function coerced it to a valid column name with no quotes
   X.col1.
1        1
2        2
3        3
4        4
5        5
6        6
7        7
8        8
9        9
10      10

So we can bypass the validity checks. Now we need escapes preceding the quotes:

df2 <- data.frame("\"col1\""=1:10, check.names=FALSE)
> df2[["\"col1\""]]
 [1]  1  2  3  4  5  6  7  8  9 10

If the df[[var]]$x approach worked for you, then the answer is more likely that df is not a dataframe but rather is an ordinary R named list and that it is x that is a dataframe. You should check this by doing:

str(df)

You could make such a structure very simply with:

> df3 <- list( item=data.frame(x=1:10, check.names=FALSE))
> var1 = "item"
> df3[[var1]]$x
 [1]  1  2  3  4  5  6  7  8  9 10
>  str(df3)
List of 1
 $ item:'data.frame':   10 obs. of  1 variable:
  ..$ x: int [1:10] 1 2 3 4 5 6 7 8 9 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM