将两个具有相同列名的数据框合并为一个具有两个值的向量的数据框

时间:2019-01-22 07:04:51

标签: r dataframe merge

我有两个数据框,一个文本,另一个是评分:

structure(list(Jessica = "tame.", Ashley = "The only"), .Names = c("Jessica", 
"Ashley"), row.names = c(NA, -1L), class = c("tbl_df", "tbl", 
"data.frame"))

structure(list(Jessica = 3L, Ashley = 1L), .Names = c("Jessica", 
"Ashley"), row.names = c(NA, -1L), class = c("tbl_df", "tbl", 
"data.frame")

我希望创建一个数据框,其中每个单元格是两个值的向量,以便我可以轻松地将其转换为具有相同键下文本和等级的json文件。

这是它的外观:

structure(list(list = list(c("tame.", "3", "The only", "1"))), class = "data.frame", row.names = c(NA, 
-1L), .Names = "list")

2 个答案:

答案 0 :(得分:0)

您可以先转换为长整(gather)并合并,即

library(tidyverse)

d1 %>% 
 gather(var, val) %>% 
 left_join(d2 %>% gather(var, val), by = 'var')

给出,

# A tibble: 2 x 3
  var     val.x    val.y
  <chr>   <chr>    <int>
1 Jessica tame.        3
2 Ashley  The only     1

答案 1 :(得分:0)

library(tidyverse)

ds1 <- structure(list(Jessica = "tame.", Ashley = "The only"), .Names = c("Jessica", 
"Ashley"), row.names = c(NA, -1L), class = c("tbl_df", "tbl", 
"data.frame"))

ds2 <- structure(list(Jessica = 3L, Ashley = 1L), .Names = c("Jessica", 
"Ashley"), row.names = c(NA, -1L), class = c("tbl_df", "tbl", 
"data.frame")
)

ds2 <- ds2 %>% mutate_all(as.character)

ds3 <- bind_rows(ds1, ds2)

(ds4 <- 
    ds3 %>% 
    gather(Jessica:Ashley, key = name, value = value) %>% 
    group_by(name) %>% 
    summarise(list = list(value)) %>% 
    ungroup() %>% 
    select(list)
)

ds4$list[1]