Nithya Ramaswamy
Nithya Ramaswamy

Reputation: 1

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 ?

Upvotes: 0

Views: 615

Answers (4)

Martin Gal
Martin Gal

Reputation: 16998

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

Upvotes: 2

prmlmu
prmlmu

Reputation: 663

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

Upvotes: 0

slava-kohut
slava-kohut

Reputation: 4233

Use t and set names:

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

Output

#   Monday Tuesday Wednesday Thursday
#     75      83        90       40

Upvotes: 1

akrun
akrun

Reputation: 887881

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))

Upvotes: 2

Related Questions