Reputation: 1
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
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
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
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
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)))
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