我希望能够获取格式相同但来自不同来源的数据,并将行连接起来,但是要跟踪数据的来源,我还想介绍一个源列。
这似乎是例行公事,所以我想我应该创建一个实用程序函数来完成它,但是我很难让它开始工作。
以下是我尝试过的:
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是否已经有能够实现这一目标的功能?有比我尝试创建的实用程序函数更好的方法吗?有办法纠正我的做法吗?
非常感谢你读了我的问题
发布于 2021-06-02 15:22:07
可以这样做:
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发布于 2021-06-02 15:30:09
如果您真的希望您的函数签名与...一起使用,则可以使用
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')
}发布于 2021-06-02 15:47:34
我们可以使用lazyeval包:一种使用公式进行非标准评估的替代方法。提供LISP样式‘准引号’的完整实现,使与其他代码一起生成代码更容易。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`https://stackoverflow.com/questions/67807951
复制相似问题