首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >函数将数据行与R(和tidyverse)中的附加源列连接起来。

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

Stack Overflow用户
提问于 2021-06-02 15:16:57
回答 4查看 242关注 0票数 1

我希望能够获取格式相同但来自不同来源的数据,并将行连接起来,但是要跟踪数据的来源,我还想介绍一个源列。

这似乎是例行公事,所以我想我应该创建一个实用程序函数来完成它,但是我很难让它开始工作。

以下是我尝试过的:

代码语言:javascript
运行
复制
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

是否已经有能够实现这一目标的功能?有比我尝试创建的实用程序函数更好的方法吗?有办法纠正我的做法吗?

非常感谢你读了我的问题

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2021-06-02 15:22:07

可以这样做:

代码语言:javascript
运行
复制
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

如果您没有输入名称:

代码语言:javascript
运行
复制
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
票数 1
EN

Stack Overflow用户

发布于 2021-06-02 15:30:09

如果您真的希望您的函数签名与...一起使用,则可以使用

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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')
}
票数 0
EN

Stack Overflow用户

发布于 2021-06-02 15:47:34

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

代码语言:javascript
运行
复制
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)

输出:

代码语言:javascript
运行
复制
      a     b ref      
  <dbl> <dbl> <chr>    
1     1     2 `tibble1`
2     3     4 `tibble1`
3     5     6 `tibble2`
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67807951

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档