how to spread or cast multiple values in r [duplicate]

纵然是瞬间 提交于 2019-11-27 09:06:16

We could do this using dplyr/tidyr. We reshape the 'data' from 'wide' to 'long' format with gather specifying the columns (starts_with('value')) to be combined to a key/value column pair ('Var/Val'), unite the 'Var' and 'y' column to create a single 'Var1' column, and reconvert back to 'wide' format with spread.

 library(dplyr)
 library(tidyr)
 data %>%
      gather(Var, val, starts_with("value")) %>% 
      unite(Var1,Var, y) %>% 
      spread(Var1, val)

 #      x value.1_a value.1_b value.1_c value.1_d value.2_a value.2_b   value.2_c
 #1   blue         5         6         7         8        17        18        19
 #2  green         9        10        11        12        21        22        23
 #3    red         1         2         3         4        13        14        15
 #    value.2_d
 #1        20
 #2        24
 #3        16

Update

(After 6 months)

Reshaping multiple value columns to wide is now possible with dcast from data.table_1.9.5 without using the melt. We can install the devel version from here

 library(data.table)
 dcast(setDT(data), x~y, value.var=c('value.1', 'value.2'))
 #       x a_value.1 b_value.1 c_value.1 d_value.1 a_value.2 b_value.2 c_value.2
 #1:  blue         5         6         7         8        17        18        19
 #2: green         9        10        11        12        21        22        23
 #3:   red         1         2         3         4        13        14        15
 #   d_value.2
 #1:        20
 #2:        24
 #3:        16

melt first then dcast:

library(reshape2)
data1 <- melt(data, id.vars = c("x", "y"))
dcast(data1, x ~ variable + y)
#      x value.1_a value.1_b value.1_c value.1_d value.2_a value.2_b value.2_c value.2_d
#1  blue         5         6         7         8        17        18        19        20
#2 green         9        10        11        12        21        22        23        24
#3   red         1         2         3         4        13        14        15        16
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!