【问题标题】:R: "stack" columns on top of each otherR:彼此“堆叠”列
【发布时间】:2021-03-20 09:52:45
【问题描述】:

假设我有一些这样的数据:

library(dplyr)

a = data.frame( "col" = c("red", "red", "green"), "coll" = c("blue", "blue", "yellow"))

我正在尝试从“a”中获取所有唯一值并将它们放入一个新框架中:

final = data.frame("col" = c("red", "green", "blue", "yellow")

我尝试了以下方法:

first_col = a %>% distinct(col)
second_col = a %>% distinct(coll)

final = cbind(first_col, second_col)

但这似乎并不正确。

谁能告诉我我做错了什么?

谢谢

【问题讨论】:

  • rbind 然后 distinct 就可以了
  • 我尝试了“rbind”但它不起作用:final = rbind(first_col, second_col) match.names(clabs, names(xi)) 中的错误:名称与以前的名称不匹配

标签: r dplyr distinct data-manipulation


【解决方案1】:

您可以将数据框unlist 转换为向量并从中获取unique 值。

final <- data.frame(col = unique(unlist(a)))
final
#     col
#1    red
#2  green
#3   blue
#4 yellow

一般的tidyverse 解决方案是获取长格式数据并获取distinct 值。

library(dplyr)
library(tidyr)

a %>%
  pivot_longer(cols = everything()) %>%
  distinct(value)

【讨论】:

    【解决方案2】:

    我们可以转换成matrix,然后用c连接成一个向量

    data.frame(col = unique(c(as.matrix(a))))
    

    【讨论】:

      【解决方案3】:

      您可以使用unionReduce 来制作它

      > data.frame(a = Reduce(union, a))
             a
      1    red
      2  green
      3   blue
      4 yellow
      

      【讨论】:

        猜你喜欢
        • 2021-10-02
        • 2019-10-19
        • 2018-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多