首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
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

Stack Overflow用户

发布于 2021-06-02 17:04:53

另一个选择是rbindlist

代码语言:javascript
运行
复制
library(data.table)
rbindlist(list(tibble1, tibble2), idcol = 'source')
票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67807951

复制
相关文章

相似问题

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