R:"stack" 列彼此重叠
R: "stack" columns on top of each other
假设我有这样的数据:
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)
但这似乎不正确。
有人可以告诉我我做错了什么吗?
谢谢
您可以 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)
我们可以转换为 matrix
,然后用 c
连接成一个向量
data.frame(col = unique(c(as.matrix(a))))
您可以使用 union
和 Reduce
来制作
> data.frame(a = Reduce(union, a))
a
1 red
2 green
3 blue
4 yellow
假设我有这样的数据:
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)
但这似乎不正确。
有人可以告诉我我做错了什么吗?
谢谢
您可以 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)
我们可以转换为 matrix
,然后用 c
data.frame(col = unique(c(as.matrix(a))))
您可以使用 union
和 Reduce
来制作
> data.frame(a = Reduce(union, a))
a
1 red
2 green
3 blue
4 yellow