英文:
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 <- tibble(A = letters[1:4],
B = letters[5:8])
y <- tibble(A = letters[9:12],
B = letters[13:16])
I'd like to obtain
# A 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
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 %>%
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
答案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 <- as.data.frame(x)
z[] <- paste(unlist(x), unlist(y), sep = ",")
# If you need tibble as output.
tibble::tibble(z)
# A 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
答案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=",")
答案4
得分: 0
这是另一种选项,不依赖于x
和y
的顺序相同:
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 = ",")))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论