【问题标题】:Dynamically select data frame columns using $ and a character value使用 $ 和字符值动态选择数据框列
【发布时间】:2013-08-15 20:21:06
【问题描述】:

我有一个包含不同列名的向量,我希望能够遍历它们中的每一个以从 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]), ]
}

【问题讨论】:

    标签: r dataframe r-faq


    【解决方案1】:

    如果我理解正确,您有一个包含变量名称的向量,并且希望遍历每个名​​称并按它们对您的数据框进行排序。如果是这样,这个例子应该为你说明一个解决方案。您的主要问题(完整示例不完整,因此我不确定您可能还缺少什么)是它应该是 order(Q1_R1000[,parameter[X]]) 而不是 order(Q1_R1000$parameter[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
    

    【讨论】:

      【解决方案2】:

      你不能用$ 做那种子集。在源代码 (R/src/main/subset.c) 中声明:

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

      第二个参数?什么?!你必须意识到$,就像 R 中的所有其他东西一样,(包括例如(+^ 等)是一个函数,它接受参数并被评估。 df$V1 可以改写为

      `$`(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
      

      【讨论】:

      • 从那以后这种情况有变化吗?
      • 我刚遇到同样的问题,'do.call' 很有帮助,这是我的代码:df[do.call(order, df[cols]), ]
      【解决方案3】:
      mtcars[do.call(order, mtcars[cols]), ]
      

      【讨论】:

        【解决方案4】:

        使用 dplyr 为数据帧排序提供了一种简单的语法

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

        使用 NSE 版本 as shown here 允许动态构建排序列表可能很有用

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

        【讨论】:

        【解决方案5】:

        由于某些 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]))
        }
        

        【讨论】:

          【解决方案6】:

          如果你想选择具有特定名称的列,那么就这样做

          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
          

          同样,这也可以在循环中添加

          【讨论】:

          • 我不知道为什么投了反对票,但它的工作原理和简单的方法而不是编写复杂的函数
          【解决方案7】:

          另一种解决方案是使用#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
          

          【讨论】:

            【解决方案8】:

            为时已晚..但我想我有答案了 -

            这是我的示例 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
            > 
            

            【讨论】:

              【解决方案9】:

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

              DT[[x]]
              

              DT[,..x]
              

              当您有 2 个或更多列要参考时,请务必使用:

              DT[,..x]
              

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

              【讨论】:

                猜你喜欢
                相关资源
                最近更新 更多