简体   繁体   English

R 将列名传递给 function 不作为字符串

[英]R pass column names to a function not as string

I am trying to pass column names to the following function.我正在尝试将列名传递给以下 function。

unnest_dt <- function(tbl, ...) {
    tbl <- as.data.table(tbl)
    col <- ensyms(...)
    clnms <- syms(setdiff(colnames(tbl), as.character(col)))
    tbl <- as.data.table(tbl)
    tbl <- eval(
      expr(tbl[, lapply(.SD, unlist), by = list(!!!clnms), .SDcols = as.character(col)])
   )
   colnames(tbl) <- c(as.character(clnms), as.character(col))
   tbl
}

The function is built for unnesting data frame with multiple list columns. function 是为取消嵌套具有多个列表列的数据框而构建的。 Consider the following implementation of the function on a dummy data.考虑 function 在虚拟数据上的以下实现。

library(tibble)
df <- tibble(
  a = LETTERS[1:5],
  b = LETTERS[6:10],
  list_column_1 = list(c(LETTERS[1:5]), "F", "G", "H", "I"),
  list_column_2 = list(c(LETTERS[1:5]), "F", "G", "H", "I")
 )

df <- unnest_dt2(df,list_column_1,list_column_2)

It serves the purpose.它服务于目的。 However, I am trying to loop over this function, and I need to pass column names to it.但是,我试图遍历这个 function,我需要将列名传递给它。 For example, I want to be able to do the following:例如,我希望能够执行以下操作:

library(dplyr)
col <- colnames(df %>% select_if(is.list))
df <- unnest_dt2(df,col)

This expectedly gives the error.这预期会产生错误。 " Error in [.data.table (tbl, , lapply(.SD, unlist), by = list(a, b, list_column_1, : column or expression 3 of 'by' or 'keyby' is type list. Do not quote column names. Usage: DT[,sum(colC),by=list(colA,month(colB))] " " [.data.table (tbl, , lapply(.SD, unlist), by = list(a, b, list_column_1, : column or expression 3 of 'by' or 'keyby' 中的错误是类型列表。不要引用列名. 用法:DT[,sum(colC),by=list(colA,month(colB))] "

Would anyone know how I can proceed with this?有人知道我该怎么做吗? Any help would be greatly appreciated.任何帮助将不胜感激。

You can change the function to work with character vector.您可以更改 function 以使用字符向量。

unnest_dt <- function(tbl, ...) {
  tbl <- as.data.table(tbl)
  col <- c(...)
  clnms <- syms(setdiff(colnames(tbl), col))
  tbl <- as.data.table(tbl)
  tbl <- eval(
    expr(tbl[, lapply(.SD, unlist), by = list(!!!clnms), 
               .SDcols = as.character(col)])
  )
  colnames(tbl) <- c(as.character(clnms), as.character(col))
  tbl
}

and then use:然后使用:

unnest_dt(df,col)

#   a b list_column_1 list_column_2
#1: A F             A             A
#2: A F             B             B
#3: A F             C             C
#4: A F             D             D
#5: A F             E             E
#6: B G             F             F
#7: C H             G             G
#8: D I             H             H
#9: E J             I             I

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

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