将数据行与 R(和 tidyverse)中的附加源列连接的函数

Function to concatenate rows of data with an additional source column in R (and tidyverse)

我希望能够获取格式相同但来源不同的数据并连接行,但为了跟踪数据源我还想引入一个源列。

这看起来很常规,我想我会创建一个实用函数来完成它,但我无法让它工作。

这是我尝试过的:

library(tidyverse)

tibble1 = tribble(
  ~a, ~b,
  1,2,
  3,4
)

tibble2 = tribble(
  ~a, ~b,
  5,6
)

bind_rows_with_source <- function(...){
  out = tibble()
  for (newtibb in list(...)){
    out <- bind_rows(out, newtibb %>% mutate(source = deparse(substitute(newtibb))))
  }
  return(out)
}

bind_rows_with_source(tibble1,tibble2)
#source column just contains the string 'newtibb' on all rows
#I want it to contain tibble1 for the first two rows and tibble2 for the third:
#~a, ~b, ~source
# 1,  2, tibble1
# 3,  4, tibble1
# 5,  6, tibble2

是否已经有可以实现此功能的功能? 有没有比我尝试创建的效用函数更好的方法? 有没有办法纠正我的做法?

衷心感谢您阅读我的问题

可以这样做:

bind_rows(list(tibble1=tibble1, tibble2=tibble2), .id='source')
# A tibble: 3 x 3
  source      a     b
  <chr>   <dbl> <dbl>
1 tibble1     1     2
2 tibble1     3     4
3 tibble2     5     6

如果您指的是不输入姓名:

bind_rows_with_source <- function(..., .id = 'source'){
  bind_rows(setNames(list(...), as.character(substitute(...()))), .id = .id)
}

bind_rows_with_source(tibble1,tibble2)
# A tibble: 3 x 3
  source      a     b
  <chr>   <dbl> <dbl>
1 tibble1     1     2
2 tibble1     3     4
3 tibble2     5     6

如果你真的想让你的函数签名与...一起使用,你可以使用

bind_rows_with_source <- function(...){
  tibbleNames <- as.character(unlist(as.list(match.call())[-1]))
  tibbleList <- setNames(lapply(tibbleNames,get),tibbleNames)
  sourceCol <- rep(tibbleNames,times=sapply(tibbleList,NROW))
  out <- do.call("rbind",tibbleList)
  out$source <- sourceCol
  return(out)
}

或者如果你可以使用 dplyr

bind_rows_with_source <- function(...){
  tibbleNames <- as.character(unlist(as.list(match.call())[-1]))
  tibbleList <- setNames(lapply(tibbleNames,get),tibbleNames)
  dplyr::bind_rows(tibbleList, .id='source')
}

我们可以使用 lazyeval 包:一种使用公式进行非标准评估的替代方法。提供LISP风格的完整实现'quasiquotation',更容易与其他代码生成代码。 https://cran.r-project.org/web/packages/lazyeval/lazyeval.pdf

library(lazyeval)
my_function <- function(df) {
  df <- df %>% mutate(ref = expr_label(df))
  return(df)
}

a <- my_function(tibble1)
b <- my_function(tibble2)
bind_rows(a, b)

输出:

      a     b ref      
  <dbl> <dbl> <chr>    
1     1     2 `tibble1`
2     3     4 `tibble1`
3     5     6 `tibble2`

另一种选择是rbindlist

library(data.table)
rbindlist(list(tibble1, tibble2), idcol = 'source')