Tom
Tom

Reputation: 75

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

Upvotes: 2

Views: 63

Answers (2)

MKR
MKR

Reputation: 20095

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)

Upvotes: 0

MrFlick
MrFlick

Reputation: 206242

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)

Upvotes: 4

Related Questions