Partial data frame transfer

I have a data frame with such data:

A   B   C   D
a1  b1  c1  d1
a1  b1  c2  d2
a1  b1  c3  d3
a2  b2  c1  d1
a2  b2  c3  d3

How can I convert this to?

A   B   c1  c2  c3
a1  b1  d1  d2  d3
a2  b2  d1      d3
+4
source share
2 answers

In the R database, you can use reshape():

reshape(mydf, direction = "wide", idvar = c("A", "B"), timevar = "C")
#    A  B D.c1 D.c2 D.c3
# 1 a1 b1   d1   d2   d3
# 4 a2 b2   d1 <NA>   d3

You can also use tidyrand dplyrtogether, for example:

library(dplyr)
# devtools::install_github("hadley/tidyr")
library(tidyr)
mydf %>% group_by(A, B) %>% spread(C, D)
# Source: local data frame [2 x 5]
# 
#    A  B c1 c2 c3
# 1 a1 b1 d1 d2 d3
# 2 a2 b2 d1 NA d3
+7
source

This is a good place to use the library reshape2. You can just do

library(reshape2)
dcast(dd, A+B~C)

To obtain

   A  B c1   c2 c3
1 a1 b1 d1   d2 d3
2 a2 b2 d1 <NA> d3

optional.

+5
source

Source: https://habr.com/ru/post/1548271/


All Articles