TeeRow
TeeRow

Reputation: 13

How to transpose a column and make it a header in R

How do I reorganize the data with the first column as the header? In the iris data set, for example, I would like the three different species types to appear as headers. I see why the following doesn't work, but I am not sure of a better way to do it.

iris
iris<-iris%>%relocate(Species,.before = Sepal.Length)
iris
names(iris)<-iris%>%distinct(Species)
iris<-iris[,-1]
head(iris)

I have seen how to do it when the column that I want to make into a header contains only unique values.

I have also tried melt(), but I am not clear on how to use it, and the R documentation was not extremely useful.

melt(t(iris),"Species")

Upvotes: 1

Views: 462

Answers (2)

TarJae
TarJae

Reputation: 79311

Are you looking for something like this?

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

Upvotes: 1

akrun
akrun

Reputation: 887981

The names assignment is not correct as the distinct on 'Species' returns a data.frame/tibble with one column whereas names expect it to be a vector. Second issue is that there are 5 columns in 'iris' and assigning 3 'Species' results in imbalance of length. Here, we may need to reshape

library(dplyr)
library(tidyr)
library(data.table)
data(iris)
iris %>%
     mutate(rn = rowid(Species)) %>%
     pivot_wider(names_from = Species, values_from =1:4 )

Upvotes: 0

Related Questions