简体   繁体   中英

How do you transpose rows into columns in r?

I have this table:

ID        Day          Score
23928     Monday       75
394838    Tuesday      83
230902    Wednesday    90
329832    Thursday     40
…

and goes on, repeating day several times.

I want to transpose the day column to get this table

MONDAY   Tuesday    Wednesday …… Sunday
78        4343           343      433

Is there a way to do this in r?

We can use data.table::transpose

library(data.table)
data.table::transpose(df1[-1], make.names = 'Day')

Or using base R

as.data.frame.list(with(df1, setNames(Score, Day)))

data

df1 <- structure(list(ID = c(23928L, 394838L, 230902L, 329832L),
Day = c("Monday", 
"Tuesday", "Wednesday", "Thursday"), Score = c(75L, 83L, 90L, 
40L)), class = "data.frame", row.names = c(NA, -4L))

Assuming your data is stored in a data.frame, you could use dplyr and tidyr :

df %>% 
  select(-ID) %>%
  pivot_wider(names_from=Day, values_from=Score)

which returns

# A tibble: 1 x 4
  Monday Tuesday Wednesday Thursday
   <dbl>   <dbl>     <dbl>    <dbl>
1     75      83        90       40

Use t and set names:

setNames(as.data.frame(t(df$Score)), df$Day)

Output

#   Monday Tuesday Wednesday Thursday
#     75      83        90       40

You could use tidyr:

library(tidyr)
data <- data.frame(day = c("Monday", "Tuesday", "Wednesday", "Thursday"),
                   val = c(12,75,9,38)    )
data %>% spread(day,val)

Result:

   Monday Thursday Tuesday Wednesday
      12       38      75         9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM