使用tidyverse在R中合并两个tibble。

huangapple go评论80阅读模式
英文:

Combine two tibbles in R using tidyverse

问题

我有两个tibbles

x <- tibble(A = letters[1:4],
            B = letters[5:8])
y <- tibble(A = letters[9:12],
            B = letters[13:16])

我想要得到

# 一个tibble: 4 × 2
  A     B    
  <chr> <chr>
1 a,i   i,m  
2 b,j   j,n  
3 c,k   k,o  
4 d,l   l,p 

我需要一段代码来实现,而不是硬编码列名,因为我必须处理可能有从一个到多个列的tibbles。这两个tibbles将始终具有相同数量的列和行。如果可能的话,我更愿意避免使用for循环。

谢谢,
Marco
英文:

I have 2 tibbles

x &lt;- tibble(A = letters[1:4],
            B = letters[5:8])
y &lt;- tibble(A = letters[9:12],
            B = letters[13:16])

I'd like to obtain

# A tibble: 4 &#215; 2
  A     B    
  &lt;chr&gt; &lt;chr&gt;
1 a,i   i,m  
2 b,j   j,n  
3 c,k   k,o  
4 d,l   l,p 

I need a code that does it without hardcoding the column names because I have to work on tibbles that can have from one to many columns. The 2 tibbles will always have the same number of columns and rows. I prefer to avoid for loop if possible.

Thank you,
Marco

答案1

得分: 3

一个选项可能是:

x %>%
  mutate(across(everything(), ~ paste(., y[[cur_column()]], sep = ",")))
  
  A     B    
  <chr> <chr>
1 a,i   e,m  
2 b,j   f,n  
3 c,k   g,o  
4 d,l   h,p
英文:

One option could be:

x %&gt;%
 mutate(across(everything(), ~ paste(., y[[cur_column()]], sep = &quot;,&quot;)))

  A     B    
  &lt;chr&gt; &lt;chr&gt;
1 a,i   e,m  
2 b,j   f,n  
3 c,k   g,o  
4 d,l   h,p

答案2

得分: 2

使用paste的基本R选项。

z <- as.data.frame(x)
z[] <- paste(unlist(x), unlist(y), sep = ",")
# 如果您需要tibble作为输出。
tibble::tibble(z)

# 一个tibble: 4 × 2
#  A     B    
#  <chr> <chr>
#1 a,i   e,m  
#2 b,j   f,n  
#3 c,k   g,o  
#4 d,l   h,p  

(Note: I've left the code part unchanged and only translated the surrounding text.)

英文:

A base R option using paste.

z &lt;- as.data.frame(x)
z[] &lt;- paste(unlist(x), unlist(y), sep = &quot;,&quot;)
# If you need tibble as output. 
tibble::tibble(z)

# A tibble: 4 &#215; 2
#  A     B    
#  &lt;chr&gt; &lt;chr&gt;
#1 a,i   e,m  
#2 b,j   f,n  
#3 c,k   g,o  
#4 d,l   h,p  

答案3

得分: 2

你可以使用 purr 来将这两个数据框作为列的集合进行映射:

purrr::map2_df(x, y, paste, sep=",")
英文:

You can use purr to map over the two data.frames as collections of columns

purrr::map2_df(x, y, paste, sep=&quot;,&quot;)

答案4

得分: 0

这是另一种选项,不依赖于xy的顺序相同:

library(purrr)

data.frame(map(set_names(names(x)), ~ paste(x[[.x]], y[[.x]], sep = ",")))
英文:

Here is another option that does not rely on x and y being in the same order:

library(purrr)

data.frame(map(set_names(names(x)), ~ paste(x[[.x]], y[[.x]], sep = &quot;,&quot;)))

huangapple
  • 本文由 发表于 2023年7月12日 21:28:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76671127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定