简体   繁体   中英

transpose long to wide within groups with tidyverse

I cant quite work this one out. How do I go from:

Visit Test
1     A
1     B
2     A
2     C
3     B

To:

Visit A     B     C
1     TRUE  TRUE  FALSE
2     TRUE  FALSE TRUE
3     FALSE TRUE  FALSE

With dplyr and tidyr you can do

dd %>% mutate(Value=TRUE) %>% 
  spread(Test, Value, fill=FALSE)

#   Visit     A     B     C
# 1     1  TRUE  TRUE FALSE
# 2     2  TRUE FALSE  TRUE
# 3     3 FALSE  TRUE FALSE

tested with

dd<-read.table(text="Visit Test
       1     A
       1     B
       2     A
       2     C
       3     B", header=T)

Another option is to use reshape2::dcast with fun.aggregate to check if length is greater than 0 .

library(reshape2)

dcast(df,Visit~Test, fun.aggregate = function(x)length(x)>0, value.var = "Test")

#   Visit     A     B     C
# 1     1  TRUE  TRUE FALSE
# 2     2  TRUE FALSE  TRUE
# 3     3 FALSE  TRUE FALSE

Data:

df<-read.table(text="Visit Test
1     A
1     B
2     A
2     C
3     B", 
header=TRUE, stringsAsFactor = FALSE)

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