使用$和字符值动态选择数据框列

发布于 2025-01-17 15:45:05 字数 512 浏览 2 评论 0原文

我有一个由不同列名组成的向量,我希望能够循环每个列名以从 data.frame 中提取该列。例如,考虑数据集 mtcars 和存储在字符向量 cols 中的一些变量名称。当我尝试使用 cols 的动态子集从 mtcars 中选择变量时,这些都不起作用,

cols <- c("mpg", "cyl", "am")
col <- cols[1]
col
# [1] "mpg"

mtcars$col
# NULL
mtcars$cols[1]
# NULL

相同的值

mtcars$mpg

我怎样才能让它们返回与此外我如何循环 遍历 cols 中的所有列以获取某种循环中的值。

for(x in seq_along(cols)) {
   value <- mtcars[ order(mtcars$cols[x]), ]
}

I have a vector of different column names and I want to be able to loop over each of them to extract that column from a data.frame. For example, consider the data set mtcars and some variable names stored in a character vector cols. When I try to select a variable from mtcars using a dynamic subset of cols, nether of these work

cols <- c("mpg", "cyl", "am")
col <- cols[1]
col
# [1] "mpg"

mtcars$col
# NULL
mtcars$cols[1]
# NULL

how can I get these to return the same values as

mtcars$mpg

Furthermore how can I loop over all the columns in cols to get the values in some sort of loop.

for(x in seq_along(cols)) {
   value <- mtcars[ order(mtcars$cols[x]), ]
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

以歌曲疗慰 2025-01-24 15:45:06

由于某些CSV文件具有相同的同一列的各种名称,因此存在类似的问题。
这是解决方案:

我写了一个函数,以返回列表中的第一个有效列名,然后使用该函数...

# Return the string name of the first name in names that is a column name in tbl
# else null
ChooseCorrectColumnName <- function(tbl, names) {
for(n in names) {
    if (n %in% colnames(tbl)) {
        return(n)
    }
}
return(null)
}

then...

cptcodefieldname = ChooseCorrectColumnName(file, c("CPT", "CPT.Code"))
icdcodefieldname = ChooseCorrectColumnName(file, c("ICD.10.CM.Code", "ICD10.Code"))

if (is.null(cptcodefieldname) || is.null(icdcodefieldname)) {
        print("Bad file column name")
}

# Here we use the hash table implementation where 
# we have a string key and list value so we need actual strings,
# not Factors
file[cptcodefieldname] = as.character(file[cptcodefieldname])
file[icdcodefieldname] = as.character(file[icdcodefieldname])
for (i in 1:length(file[cptcodefieldname])) {
    cpt_valid_icds[file[cptcodefieldname][i]] <<- unique(c(cpt_valid_icds[[file[cptcodefieldname][i]]], file[icdcodefieldname][i]))
}

Had similar problem due to some CSV files that had various names for the same column.
This was the solution:

I wrote a function to return the first valid column name in a list, then used that...

# Return the string name of the first name in names that is a column name in tbl
# else null
ChooseCorrectColumnName <- function(tbl, names) {
for(n in names) {
    if (n %in% colnames(tbl)) {
        return(n)
    }
}
return(null)
}

then...

cptcodefieldname = ChooseCorrectColumnName(file, c("CPT", "CPT.Code"))
icdcodefieldname = ChooseCorrectColumnName(file, c("ICD.10.CM.Code", "ICD10.Code"))

if (is.null(cptcodefieldname) || is.null(icdcodefieldname)) {
        print("Bad file column name")
}

# Here we use the hash table implementation where 
# we have a string key and list value so we need actual strings,
# not Factors
file[cptcodefieldname] = as.character(file[cptcodefieldname])
file[icdcodefieldname] = as.character(file[icdcodefieldname])
for (i in 1:length(file[cptcodefieldname])) {
    cpt_valid_icds[file[cptcodefieldname][i]] <<- unique(c(cpt_valid_icds[[file[cptcodefieldname][i]]], file[icdcodefieldname][i]))
}
忘羡 2025-01-24 15:45:06
mtcars[do.call(order, mtcars[cols]), ]
mtcars[do.call(order, mtcars[cols]), ]
愛上了 2025-01-24 15:45:06

我身上发生过好几次。使用 data.table 包。当您只有 1 列需要参考时。使用

DT[[x]]

DT[,..x]

当您有 2 个或更多列要引用时,请确保使用:

DT[,..x]

x 可以是另一个 data.frame 中的字符串。

Happened to me several times. Use data.table package. When you only have 1 column that you need to refer to. Use either

DT[[x]]

or

DT[,..x]

When you have 2 or more columns to refer to, make sure to use:

DT[,..x]

That x can be strings in another data.frame.

原来是傀儡 2025-01-24 15:45:06

太晚了..但我想我已经有了答案 -

这是我的示例 Study.df 数据框 -

   >study.df
   study   sample       collection_dt other_column
   1 DS-111 ES768098 2019-01-21:04:00:30         <NA>
   2 DS-111 ES768099 2018-12-20:08:00:30   some_value
   3 DS-111 ES768100                <NA>   some_value

然后 -

> ## Selecting Columns in an Given order
> ## Create ColNames vector as per your Preference
> 
> selectCols <- c('study','collection_dt','sample')
> 
> ## Select data from Study.df with help of selection vector
> selectCols %>% select(.data=study.df,.)
   study       collection_dt   sample
1 DS-111 2019-01-21:04:00:30 ES768098
2 DS-111 2018-12-20:08:00:30 ES768099
3 DS-111                <NA> ES768100
> 

too late.. but I guess I have the answer -

Here's my sample study.df dataframe -

   >study.df
   study   sample       collection_dt other_column
   1 DS-111 ES768098 2019-01-21:04:00:30         <NA>
   2 DS-111 ES768099 2018-12-20:08:00:30   some_value
   3 DS-111 ES768100                <NA>   some_value

And then -

> ## Selecting Columns in an Given order
> ## Create ColNames vector as per your Preference
> 
> selectCols <- c('study','collection_dt','sample')
> 
> ## Select data from Study.df with help of selection vector
> selectCols %>% select(.data=study.df,.)
   study       collection_dt   sample
1 DS-111 2019-01-21:04:00:30 ES768098
2 DS-111 2018-12-20:08:00:30 ES768099
3 DS-111                <NA> ES768100
> 
猫卆 2025-01-24 15:45:06

如果您想选择具有特定名称的列,那么

A <- mtcars[,which(conames(mtcars)==cols[1])]
# and then
colnames(mtcars)[A]=cols[1]

您也可以循环运行它
添加动态名称的反向方法,例如,如果 A 是数据框,xyz 是要命名为 x 的列,那么我

A$tmp <- xyz
colnames(A)[colnames(A)=="tmp"]=x

再次喜欢这样,这也可以在循环中添加

if you want to select column with specific name then just do

A <- mtcars[,which(conames(mtcars)==cols[1])]
# and then
colnames(mtcars)[A]=cols[1]

you can run it in loop as well
reverse way to add dynamic name eg if A is data frame and xyz is column to be named as x then I do like this

A$tmp <- xyz
colnames(A)[colnames(A)=="tmp"]=x

again this can also be added in loop

So尛奶瓶 2025-01-24 15:45:05

您无法使用 $ 进行此类子集化。在源代码 (R/src/main/subset.c) 中,它指出:

/*$ 子集运算符。
我们需要确保只评估第一个参数。
第二个是需要匹配而不是求值的符号。
*/

第二个参数?什么?!您必须意识到 $ 与 R 中的其他所有内容一样(包括例如 (+^ etc) 是一个函数,它接受参数并进行计算,实际上可以重写为

`

您无法使用 $ 进行此类子集化。在源代码 (R/src/main/subset.c) 中,它指出:

/*$ 子集运算符。
我们需要确保只评估第一个参数。
第二个是需要匹配而不是求值的符号。
*/

第二个参数?什么?!您必须意识到 $ 与 R 中的其他所有内容一样(包括例如 (+^ etc) 是一个函数,它接受参数并进行计算,实际上可以重写为

(df , V1)

`

您无法使用 $ 进行此类子集化。在源代码 (R/src/main/subset.c) 中,它指出:

/*$ 子集运算符。
我们需要确保只评估第一个参数。
第二个是需要匹配而不是求值的符号。
*/

第二个参数?什么?!您必须意识到 $ 与 R 中的其他所有内容一样(包括例如 (+^ etc) 是一个函数,它接受参数并进行计算,实际上可以重写为

`

您无法使用 $ 进行此类子集化。在源代码 (R/src/main/subset.c) 中,它指出:

/*$ 子集运算符。
我们需要确保只评估第一个参数。
第二个是需要匹配而不是求值的符号。
*/

第二个参数?什么?!您必须意识到 $ 与 R 中的其他所有内容一样(包括例如 (+^ etc) 是一个函数,它接受参数并进行计算,实际上可以重写为

(df , V1)

(df , "V1")

但是...

`

您无法使用 $ 进行此类子集化。在源代码 (R/src/main/subset.c) 中,它指出:

/*$ 子集运算符。
我们需要确保只评估第一个参数。
第二个是需要匹配而不是求值的符号。
*/

第二个参数?什么?!您必须意识到 $ 与 R 中的其他所有内容一样(包括例如 (+^ etc) 是一个函数,它接受参数并进行计算,实际上可以重写为

`

您无法使用 $ 进行此类子集化。在源代码 (R/src/main/subset.c) 中,它指出:

/*$ 子集运算符。
我们需要确保只评估第一个参数。
第二个是需要匹配而不是求值的符号。
*/

第二个参数?什么?!您必须意识到 $ 与 R 中的其他所有内容一样(包括例如 (+^ etc) 是一个函数,它接受参数并进行计算,实际上可以重写为

(df , V1)

`

您无法使用 $ 进行此类子集化。在源代码 (R/src/main/subset.c) 中,它指出:

/*$ 子集运算符。
我们需要确保只评估第一个参数。
第二个是需要匹配而不是求值的符号。
*/

第二个参数?什么?!您必须意识到 $ 与 R 中的其他所有内容一样(包括例如 (+^ etc) 是一个函数,它接受参数并进行计算,实际上可以重写为

`

您无法使用 $ 进行此类子集化。在源代码 (R/src/main/subset.c) 中,它指出:

/*$ 子集运算符。
我们需要确保只评估第一个参数。
第二个是需要匹配而不是求值的符号。
*/

第二个参数?什么?!您必须意识到 $ 与 R 中的其他所有内容一样(包括例如 (+^ etc) 是一个函数,它接受参数并进行计算,实际上可以重写为

(df , V1)

(df , "V1")

但是...

(df , paste0("V1") )

...例如永远不会工作,其他任何必须首先执行的操作也不会工作。您只能传递一个字符串,该字符串是第二个参数。 从不评估,

而是使用[(或者如果您只想提取单个列作为向量)。 )

例如,

var <- "mpg"
#Doesn't work
mtcars$var
#These both work, but note that what they return is different
# the first is a vector, the second is a data.frame
mtcars[[var]]
mtcars[var]

您可以使用 do.call 构造对 order 的调用来执行排序,如下所示:

#  set seed for reproducibility
set.seed(123)
df <- data.frame( col1 = sample(5,10,repl=T) , col2 = sample(5,10,repl=T) , col3 = sample(5,10,repl=T) )

#  We want to sort by 'col3' then by 'col1'
sort_list <- c("col3","col1")

#  Use 'do.call' to call order. Seccond argument in do.call is a list of arguments
#  to pass to the first argument, in this case 'order'.
#  Since  a data.frame is really a list, we just subset the data.frame
#  according to the columns we want to sort in, in that order
df[ do.call( order , df[ , match( sort_list , names(df) ) ]  ) , ]

   col1 col2 col3
10    3    5    1
9     3    2    2
7     3    2    3
8     5    1    3
6     1    5    4
3     3    4    4
2     4    3    4
5     5    1    4
1     2    5    5
4     5    3    5

You can't do that kind of subsetting with $. In the source code (R/src/main/subset.c) it states:

/*The $ subset operator.
We need to be sure to only evaluate the first argument.
The second will be a symbol that needs to be matched, not evaluated.
*/

Second argument? What?! You have to realise that $, like everything else in R, (including for instance ( , + , ^ etc) is a function, that takes arguments and is evaluated. df$V1 could be rewritten as

`

You can't do that kind of subsetting with $. In the source code (R/src/main/subset.c) it states:

/*The $ subset operator.
We need to be sure to only evaluate the first argument.
The second will be a symbol that needs to be matched, not evaluated.
*/

Second argument? What?! You have to realise that $, like everything else in R, (including for instance ( , + , ^ etc) is a function, that takes arguments and is evaluated. df$V1 could be rewritten as

(df , V1)

or indeed

`

You can't do that kind of subsetting with $. In the source code (R/src/main/subset.c) it states:

/*The $ subset operator.
We need to be sure to only evaluate the first argument.
The second will be a symbol that needs to be matched, not evaluated.
*/

Second argument? What?! You have to realise that $, like everything else in R, (including for instance ( , + , ^ etc) is a function, that takes arguments and is evaluated. df$V1 could be rewritten as

`

You can't do that kind of subsetting with $. In the source code (R/src/main/subset.c) it states:

/*The $ subset operator.
We need to be sure to only evaluate the first argument.
The second will be a symbol that needs to be matched, not evaluated.
*/

Second argument? What?! You have to realise that $, like everything else in R, (including for instance ( , + , ^ etc) is a function, that takes arguments and is evaluated. df$V1 could be rewritten as

(df , V1)

or indeed

(df , "V1")

But...

`

You can't do that kind of subsetting with $. In the source code (R/src/main/subset.c) it states:

/*The $ subset operator.
We need to be sure to only evaluate the first argument.
The second will be a symbol that needs to be matched, not evaluated.
*/

Second argument? What?! You have to realise that $, like everything else in R, (including for instance ( , + , ^ etc) is a function, that takes arguments and is evaluated. df$V1 could be rewritten as

`

You can't do that kind of subsetting with $. In the source code (R/src/main/subset.c) it states:

/*The $ subset operator.
We need to be sure to only evaluate the first argument.
The second will be a symbol that needs to be matched, not evaluated.
*/

Second argument? What?! You have to realise that $, like everything else in R, (including for instance ( , + , ^ etc) is a function, that takes arguments and is evaluated. df$V1 could be rewritten as

(df , V1)

or indeed

`

You can't do that kind of subsetting with $. In the source code (R/src/main/subset.c) it states:

/*The $ subset operator.
We need to be sure to only evaluate the first argument.
The second will be a symbol that needs to be matched, not evaluated.
*/

Second argument? What?! You have to realise that $, like everything else in R, (including for instance ( , + , ^ etc) is a function, that takes arguments and is evaluated. df$V1 could be rewritten as

`

You can't do that kind of subsetting with $. In the source code (R/src/main/subset.c) it states:

/*The $ subset operator.
We need to be sure to only evaluate the first argument.
The second will be a symbol that needs to be matched, not evaluated.
*/

Second argument? What?! You have to realise that $, like everything else in R, (including for instance ( , + , ^ etc) is a function, that takes arguments and is evaluated. df$V1 could be rewritten as

(df , V1)

or indeed

(df , "V1")

But...

(df , paste0("V1") )

...for instance will never work, nor will anything else that must first be evaluated in the second argument. You may only pass a string which is never evaluated.

Instead use [ (or [[ if you want to extract only a single column as a vector).

For example,

var <- "mpg"
#Doesn't work
mtcars$var
#These both work, but note that what they return is different
# the first is a vector, the second is a data.frame
mtcars[[var]]
mtcars[var]

You can perform the ordering without loops, using do.call to construct the call to order. Here is a reproducible example below:

#  set seed for reproducibility
set.seed(123)
df <- data.frame( col1 = sample(5,10,repl=T) , col2 = sample(5,10,repl=T) , col3 = sample(5,10,repl=T) )

#  We want to sort by 'col3' then by 'col1'
sort_list <- c("col3","col1")

#  Use 'do.call' to call order. Seccond argument in do.call is a list of arguments
#  to pass to the first argument, in this case 'order'.
#  Since  a data.frame is really a list, we just subset the data.frame
#  according to the columns we want to sort in, in that order
df[ do.call( order , df[ , match( sort_list , names(df) ) ]  ) , ]

   col1 col2 col3
10    3    5    1
9     3    2    2
7     3    2    3
8     5    1    3
6     1    5    4
3     3    4    4
2     4    3    4
5     5    1    4
1     2    5    5
4     5    3    5
我要还你自由 2025-01-24 15:45:05

使用 dplyr 提供了一种简单的语法来对数据帧进行排序

library(dplyr)
mtcars %>% arrange(gear, desc(mpg))

使用 NSE 版本 可能很有用,如下所示 允许动态构建排序列表

sort_list <- c("gear", "desc(mpg)")
mtcars %>% arrange_(.dots = sort_list)

Using dplyr provides an easy syntax for sorting the data frames

library(dplyr)
mtcars %>% arrange(gear, desc(mpg))

It might be useful to use the NSE version as shown here to allow dynamically building the sort list

sort_list <- c("gear", "desc(mpg)")
mtcars %>% arrange_(.dots = sort_list)
唐婉 2025-01-24 15:45:05

如果我正确理解,您有一个包含变量名称的向量,并希望循环遍历每个名​​称并通过它们对数据框架进行整理。如果是这样,此示例应为您说明解决方案。您的主要问题(完整的示例还没有完成,所以我“不确定您还缺少什么),它应该是order(q1_r1000 [,parameter [x]])而不是订单(Q1_R1000 $参数[X]),因为参数是一个外部对象,其中包含一个与数据框架直接列相对的可变名称(当$时将是适当的)。

set.seed(1)
dat <- data.frame(var1=round(rnorm(10)),
                   var2=round(rnorm(10)),
                   var3=round(rnorm(10)))
param <- paste0("var",1:3)
dat
#   var1 var2 var3
#1    -1    2    1
#2     0    0    1
#3    -1   -1    0
#4     2   -2   -2
#5     0    1    1
#6    -1    0    0
#7     0    0    0
#8     1    1   -1
#9     1    1    0
#10    0    1    0

for(p in rev(param)){
   dat <- dat[order(dat[,p]),]
 }
dat
#   var1 var2 var3
#3    -1   -1    0
#6    -1    0    0
#1    -1    2    1
#7     0    0    0
#2     0    0    1
#10    0    1    0
#5     0    1    1
#8     1    1   -1
#9     1    1    0
#4     2   -2   -2

If I understand correctly, you have a vector containing variable names and would like loop through each name and sort your data frame by them. If so, this example should illustrate a solution for you. The primary issue in yours (the full example isn't complete so I"m not sure what else you may be missing) is that it should be order(Q1_R1000[,parameter[X]]) instead of order(Q1_R1000$parameter[X]), since parameter is an external object that contains a variable name opposed to a direct column of your data frame (which when the $ would be appropriate).

set.seed(1)
dat <- data.frame(var1=round(rnorm(10)),
                   var2=round(rnorm(10)),
                   var3=round(rnorm(10)))
param <- paste0("var",1:3)
dat
#   var1 var2 var3
#1    -1    2    1
#2     0    0    1
#3    -1   -1    0
#4     2   -2   -2
#5     0    1    1
#6    -1    0    0
#7     0    0    0
#8     1    1   -1
#9     1    1    0
#10    0    1    0

for(p in rev(param)){
   dat <- dat[order(dat[,p]),]
 }
dat
#   var1 var2 var3
#3    -1   -1    0
#6    -1    0    0
#1    -1    2    1
#7     0    0    0
#2     0    0    1
#10    0    1    0
#5     0    1    1
#8     1    1   -1
#9     1    1    0
#4     2   -2   -2
安静 2025-01-24 15:45:05

我将实现sym rlang软件包的功能。假设col具有“ mpg”的值。这个想法是将其征收。

mtcars %>% pull(!!sym(col))
#  [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7 15.0
# [32] 21.4

保持编码!

I would implement the sym function of rlang package. Let's say the col has value as "mpg". The idea is to subset it.

mtcars %>% pull(!!sym(col))
#  [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7 15.0
# [32] 21.4

Keep Coding!

好久不见√ 2025-01-24 15:45:05

另一种解决方案是使用#get:

> cols <- c("cyl", "am")
> get(cols[1], mtcars)
 [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4

Another solution is to use #get:

> cols <- c("cyl", "am")
> get(cols[1], mtcars)
 [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文