简体   繁体   English

从df中获取列名并查询df

[英]Getting column names from df and querying df

When I do: 当我做:

var = names(df)[2]

df$var

I get NULL . 我得到NULL I think that var is a string inside quotes and that is why this is happening. 我认为var是带引号的字符串,这就是为什么这种情况发生。 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],但是如果我的数据帧中包含另一个数据帧怎么办? df[var][x] or df[var]$x won't work. df [var] [x]或df [var] $ x不起作用。

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

df[[var]]

It's hard to know what error-inducing situation has been constructed without dput-output on the offending dataframe. 很难知道在没有问题的数据帧上没有dput输出的情况下构造了什么错误引发情况。 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. 如果df[[var]]$x方法对您有用,那么答案很可能是df不是数据帧,而是普通的R命名列表,而x是数据帧。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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