I've already asked a similar question last week, but I found out that I need also the ID column and I'm not able to add multiple columns in the code that the person suggested me, so I need to ask it again.
I need to transpose the data from the left table to the right table ().
data <- data.frame(
+ stringsAsFactors = FALSE,
+ ID = c(15262L,17382L,14892L,15262L,17382,14892L),
+ TEST = c("Pre", "Pre","Pre", "Post", "Post","Post"),
+ Q1 = c(2L, 5L,3L,3L,2L,4L),
+ Q2 = c(3L,4L,5L,3L,4L,5L),
+ Q3 = c(4L,3L,3L,2L,2L,1L))
>
> data
ID TEST Q1 Q2 Q3
1 15262 Pre 2 3 4
2 17382 Pre 5 4 3
3 14892 Pre 3 5 3
4 15262 Post 3 3 2
5 17382 Post 2 4 2
6 14892 Post 4 5 1
the code suggested by the person was:
library(dplyr)
library(tidyr)
data %>%
pivot_longer(-Test) %>%
pivot_wider(names_from = Test, values_from = value) %>%
unnest()
I tried to:
final_data<- data %>%
pivot_longer(cols= starts_with('Q')) %>%
pivot_wider(names_from = Test, values_from = value) %>%
unnest()
and
final_data2<- data %>%
pivot_longer(-Test,-ID) %>%
pivot_wider(names_from = Test, values_from = value) %>%
unnest()
and other combinations that I don't remember, but I continue to have some warning or error messages.
ID and Q1,Q2 etc are Double type and Test as Character,
Can someone help me??
Thank you very much!