【问题标题】:Merging two columns of type factor合并两列类型因子
【发布时间】:2017-05-09 21:36:39
【问题描述】:

我想用unique 因子将两列不同长度的列合并到一列中,示例如下:

list1 <- as.factor(c('1a','2r','6t'))
list2 <- as.factor(c('1a','5p','3g','2341','7','2r'))

NewList
  1a      
  2341       
  2r        
  3g       
  5p       
  6t
  7

我尝试过rbinddata.frame,但它们似乎不适用于不同长度的列。

【问题讨论】:

    标签: r dataframe merge


    【解决方案1】:

    在基础 R 中使用 union

    data.frame(newlist=union(levels(list1), levels(list2)))
    
    #  newlist
    #1      1a
    #2      2r
    #3      6t
    #4    2341
    #5      3g
    #6      5p
    #7       7
    

    【讨论】:

    • 感谢您的回答,它运行良好,但我只有一个人提出问题。 newlistchar 但为什么 str(data.frame(...))factordata.frame 是否将值视为因素?
    • @Y.Z.如果您想将newlist 用作character,只需使用stringsAsFactors = FALSE。即data.frame(newlist=union(levels(list1), levels(list2)), stringsAsFactors = FALSE)
    • @,谢谢,有什么方法可以让我只保留两个列表之间的差异。比如把结果转成newlist &lt;- c('2341','3g','5p','6t','7')
    • 使用setdiff 而不是union。您可能希望通过单击赞成/反对图标下方的复选标记来接受我的回答。
    【解决方案2】:

    as.factor(unique(c(as.character(list1), as.character(list2))))怎么样?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多