使用full_join合并两个以上数据帧时的后缀 [英] Suffixes when merging more than two data frames with full_join

查看:78
本文介绍了使用full_join合并两个以上数据帧时的后缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用嵌套的full_join将几个数据帧合并在一起.另外,我希望能够为所有列添加后缀,以便在合并数据帧时,每个列名都指示其来自哪个数据帧(例如,唯一的时间标识符,例如T1,T2,... ).

I would like to used nested full_join to merge several data frames together. In addition, I am hoping to be able to add suffixes to all of the columns so that when the data frames are merged each column name indicates which data frame it came from (e.g., a unique time identifier like T1, T2, ...).

x <- data.frame(i = c("a","b","c"), j = 1:3, h = 1:3, stringsAsFactors=FALSE)
y <- data.frame(i = c("b","c","d"), k = 4:6, h = 1:3, stringsAsFactors=FALSE)
z <- data.frame(i = c("c","d","a"), l = 7:9, h = 1:3, stringsAsFactors=FALSE)

full_join(x, y, by='i') %>% left_join(., z, by='I')

有没有一种方法可以集成默认的后缀选项,以便获得具有列名称的数据集,如下所示:

Is there a way to integrate the default suffix option so that I get a dataset with column names that look like:

column_names <- c("i", "j_T1", "h_T1", "k_T2", "h_T2", "l_T3", "h_T3")

推荐答案

我认为可以通过使用purrr使用列标题来完成此操作,但是我已经使用ivot_wider和pivot_longer来更改标题名称:

I think this can be done by working with the column headers using purrr but I've used pivot_wider and pivot_longer to change the header names:

df <- x %>% 
  full_join(y, by = "i") %>% 
  full_join(z, by = "i") %>% 
  pivot_longer(cols = -i,
               names_to = "columns",
               values_to = "values") %>% # makes the column headers into a column 
which can be changed
  mutate(columns = str_replace(columns, ".x", "_T2"),
         columns = str_replace(columns, ".y", "_T3"),
         columns = case_when(!str_detect(columns, "T") ~ paste0(columns, "_T1"),
                             TRUE ~ columns)) %>% 
  pivot_wider(names_from = columns,
              values_from = values)

这些与列出的标题不匹配,但是如果顺序很重要并且l列应为T3(此示例中只有1),则希望该代码有助于您入门.

These don't match the listed headers but hopefully this code will help to get you started if the order is important and column l should be T3 (there was only 1 in this example).

这篇关于使用full_join合并两个以上数据帧时的后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆