1

I'm using the below method to cast variables in a dataframe from long to wide format. However, I'm looking for an alternative way, using another package. Any help is much appreciated?

subject <- c(1:10, 1:10)
condition <- c(rep(1,10), rep(2,10))
value <- c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
rating <- c(1, 3, 5, 2, 3, 5, 6, 7, 5, 3, 5, 7, 3, 6, 3, 5, 6, 7, 7, 8)
df <- data.frame(subject, condition, value, rating)

library(data.table)
df_wide <- dcast(setDT(df), subject ~ condition, value.var=c("rating", "value"))
David Arenburg
  • 87,271
  • 15
  • 123
  • 181
Blixten
  • 45
  • 7
  • 2
    Um, file a bug report and/or use a version of data.table that you know to be stable? – Frank Jun 04 '17 at 17:37
  • 1
    Good point! Did not think about that; but I've seen posts that other people have had the same error like me but their solutions have not worked for me... – Blixten Jun 04 '17 at 18:03
  • 1
    When you are talking about errors, it is always good to include those error messages in your question. See also: [ask] – Jaap Jun 04 '17 at 18:29
  • I have now edited the question. I've learned not to ask several questions in "one question" and this question was never intended to be about fixing data.table but to get an alternative solution that I can use whilst trying to fix the data.table error that I have. – Blixten Jun 04 '17 at 19:05

1 Answers1

2

We can use tidyverse

library(tidyverse)
df %>% 
     gather(key, val, value:rating) %>% 
     unite(cond, key, condition) %>%
     spread(cond, val)
#     subject rating_1 rating_2 value_1 value_2
#1        1        1        5       1       1
#2        2        3        7       2       2
#3        3        5        3       3       3
#4        4        2        6       4       4
#5        5        3        3       5       5
#6        6        5        5       1       1
#7        7        6        6       2       2
#8        8        7        7       3       3
#9        9        5        7       4       4
#10      10        3        8       5       5
akrun
  • 674,427
  • 24
  • 381
  • 486