【问题标题】:Merge two dataframes with same column names into one with a vector of the two values将具有相同列名的两个数据框合并为一个具有两个值的向量的数据框
【发布时间】:2019-01-22 07:04:50
【问题描述】:

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

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")

【问题讨论】:

  • 您能否为您提供的示例数据明确添加您的预期输出?
  • 抱歉 - 我更新了我的问题。
  • 我不明白您的预期输出。在任何初始tibbles 中都没有条目"seems tame"。那是"tame."吗?为什么您的预期输出中有两个相同的 list 条目?为什么它们会重复?如果您要提供稍大(多于一行)且更具代表性的示例并匹配预期输出,也许会有所帮助。我不清楚你想做什么。
  • 谢谢 - 也许您正在查看我的更改草稿。请参阅下面乔的回复。还是谢谢。

标签: r dataframe merge


【解决方案1】:
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]

【讨论】:

  • 完美的乔!这正是我所需要的!
【解决方案2】:

您可以先转换为long(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

【讨论】:

  • 谢谢,但目标是在每个单元格中列出两个值。
猜你喜欢
  • 1970-01-01
  • 2017-06-24
  • 1970-01-01
  • 2020-12-04
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2021-01-16
  • 2015-03-21
相关资源
最近更新 更多