如何将第一列作为标题重新组织数据?例如,在iris数据集中,我希望将三种不同的物种类型显示为标题。我知道为什么下面的方法不起作用,但我不确定有更好的方法来做到这一点。
iris
iris<-iris%>%relocate(Species,.before = Sepal.Length)
iris
names(iris)<-iris%>%distinct(Species)
iris<-iris[,-1]
head(iris)
我已经看到了当我想要成为标题的列只包含唯一值时如何做到这一点。
我也尝试过melt()
,但我不清楚如何使用它,R文档不是非常有用。
melt(t(iris),"Species")
names
赋值不正确,因为'Species'上的distinct
返回具有一列的data.frame/tibble
,而names
期望它是一个向量。第二个问题是,在"iris"中有5列,分配3个"Species"导致长度不平衡。这里,我们可能需要重塑
library(dplyr)
library(tidyr)
library(data.table)
data(iris)
iris %>%
mutate(rn = rowid(Species)) %>%
pivot_wider(names_from = Species, values_from =1:4 )
你在找这样的东西吗?
iris %>% cbind(sapply(levels(.$Species), `==`, .$Species))
Sepal.Length Sepal.Width Petal.Length Petal.Width Species setosa versicolor virginica
<dbl> <dbl> <dbl> <dbl> <fct> <lgl> <lgl> <lgl>
1 5.1 3.5 1.4 0.2 setosa TRUE FALSE FALSE
2 4.9 3 1.4 0.2 setosa TRUE FALSE FALSE
3 4.7 3.2 1.3 0.2 setosa TRUE FALSE FALSE
4 4.6 3.1 1.5 0.2 setosa TRUE FALSE FALSE
5 5 3.6 1.4 0.2 setosa TRUE FALSE FALSE
6 5.4 3.9 1.7 0.4 setosa TRUE FALSE FALSE
7 4.6 3.4 1.4 0.3 setosa TRUE FALSE FALSE
8 5 3.4 1.5 0.2 setosa TRUE FALSE FALSE
9 4.4 2.9 1.4 0.2 setosa TRUE FALSE FALSE
10 4.9 3.1 1.5 0.1 setosa TRUE FALSE FALSE
# ... with 140 more rows