【问题标题】:melting two unequal data frame into one in R在R中将两个不相等的数据帧融合为一个
【发布时间】:2014-09-19 08:48:16
【问题描述】:

我有两个这样的 excel 文件作为数据框导入

x   title1   title2                 x  title3
1    x          y                   1    j
2    a          b                   2    m
3    i          j                   3    y
4    m          n          

我想把这些数据框像这样融合成一个

1   title1  x           
2   title1  a           
3   title1  i           
4   title1  m
1   title2  y
2   title2  b
3   title2  j
4   title2  n
1   title3  j
2   title3  m
3   title3  y

我应该使用 ggplot 绘制最终数据帧的图,我知道如何使用 ggplot,但我有点困惑如何将两个不相等的数据帧融合为一个 我感谢任何帮助

【问题讨论】:

  • 你不能单独融化每个然后 rbind 融化的 dfs 吗?
  • @beetroot, melt 也适用于lists,因此他们可以只创建data.frames 和meltlist

标签: r dataframe melt


【解决方案1】:

将您的data.frames 放入list 并融化它们。使用@jazzurro 的示例数据,尝试:

melt(list(foo, foo2), id.vars = "id")
#    id variable value L1
# 1   1       t1     x  1
# 2   2       t1     a  1
# 3   3       t1     i  1
# 4   4       t1     m  1
# 5   1       t2     y  1
# 6   2       t2     b  1
# 7   3       t2     j  1
# 8   4       t2     n  1
# 9   1       t3     j  2
# 10  2       t3     m  2
# 11  3       t3     y  2

更酷的是,因为它在另一列中为您提供了原始的 data.frame 名称,所以通过上述方法将 mgetls 结合使用:

melt(mget(ls(pattern = "foo")), id.vars = "id")
#    id variable value   L1
# 1   1       t1     x  foo
# 2   2       t1     a  foo
# 3   3       t1     i  foo
# 4   4       t1     m  foo
# 5   1       t2     y  foo
# 6   2       t2     b  foo
# 7   3       t2     j  foo
# 8   4       t2     n  foo
# 9   1       t3     j foo2
# 10  2       t3     m foo2
# 11  3       t3     y foo2

【讨论】:

    【解决方案2】:

    这里有一种方法。

    library(reshape2)
    library(dplyr) 
    
    id <- 1:4
    t1 <- c("x","a","i","m")
    t2 <- c("y", "b", "j", "n")
    foo <- data.frame(id, t1, t2, stringsAsFactors = FALSE)
    
    id <- 1:3
    t3 <- c("j","m","y")
    foo2 <- data.frame(id, t3, stringsAsFactors = FALSE)
    
    foo %>%
        merge(., foo2, by = "id", all = TRUE) %>%
        melt(., id.vars = "id") %>%
        filter(!value %in% NA)
    
       id variable value
    1   1       t1     x
    2   2       t1     a
    3   3       t1     i
    4   4       t1     m
    5   1       t2     y
    6   2       t2     b
    7   3       t2     j
    8   4       t2     n
    9   1       t3     j
    10  2       t3     m
    11  3       t3     y
    

    【讨论】:

    • +1,也许你可以使用left_joingatherdplyr/tidyr独有的方法
    • 感谢回复,但是我的Rstudio报错,Error: could not find function "%>%",是否需要导入其他包?!
    • @akrun 谢谢。这些功能在我的脑海中。由于前几天我发布了与left_join相关的东西,我认为最好选择merge以避免潜在的错误。但是,在这里也可以使用dplyr/tidyr 函数。
    • @user3015703 你需要安装reshape2dplyr。 %>% 是您需要的运算符。一旦你上传了dplyr,你会没事的。
    猜你喜欢
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多