【问题标题】:join/merge two columns inside a data-frame加入/合并数据框中的两列
【发布时间】:2012-11-15 18:39:58
【问题描述】:

假设我有这些数据,

(df <- data.frame( col1 = c('My','Your','His','Thir'), col2 = c('Cat','Dog','Fish','Dog')))

  col1 col2
1   My  Cat
2 Your  Dog
3  His Fish
4 Thir  Dog

我想像这样合并列

`some magic`

  col1 col2      col3
1   My  Cat    My Cat
2 Your  Dog  Your Dog
3  His Fish  His Fish
4 Thir  Dog  Thir Dog

我该怎么办?甚至可以像这样使用逗号(,),

`some magic`

  col1 col2      col3
1   My  Cat    My, Cat
2 Your  Dog  Your, Dog
3  His Fish  His, Fish
4 Thir  Dog  Thir, Dog

【问题讨论】:

    标签: r join merge data-management


    【解决方案1】:

    df$col3 &lt;- paste(df$col1, df$col2, sep=",")。您还可以使用sprintfpaste0 函数。

    df$col3 <- paste(df$col1, df$col2, sep=",") # comma separator
    df$col3 <- paste0(df$col1, df$col2) # for no separator
    

    【讨论】:

    • 如果我们也处理空值怎么办?我们如何处理多余的逗号
    • 我还在等待您的回复。假设数据是col1 为空白且col2 有猫。结果值不会是, cat。如何处理?我只需要cat。如果我们使用多个列,结果甚至可能是 , , cat, , , dog
    • @Saksham ifelse 函数应该是您正在寻找的。对于多个列,您可能需要多个嵌套调用 ifelse(..., ..., ifelse(...))。对于可能为空白的一列,它看起来像ifelse(df$col1 == "", df$col2, paste(df$col1, df$col2, sep=","))
    【解决方案2】:

    如果您想将它们保留为两者的列表,(而不是连接两者的字符串),那么以下将很好用

    within(df, col3 <- Map(list, as.character(col1),as.character(col2)))  
    
      col1 col2      col3
    1   My  Cat   My, Cat
    2 Your  Dog Your, Dog
    3  His Fish His, Fish
    4 Thir  Dog Thir, Dog
    

    Mapmapply(..., SIMPLIFY = FALSE) 的简单包装器

    【讨论】:

    • 谢谢,这看起来很有趣。稍后我会玩弄它。
    • 如果我们也处理空值怎么办?我们如何处理多余的逗号
    • 我还在等待您的回复。假设数据是col1 为空白且col2 有猫。结果值不会是, cat。如何处理?我只需要cat。如果我们使用多个列,结果甚至可能是, , cat, , , dog
    猜你喜欢
    • 2020-11-13
    • 2021-11-13
    • 2013-09-18
    • 2020-05-07
    • 1970-01-01
    • 2018-10-08
    相关资源
    最近更新 更多