Change data by ID and add all values ​​belong to one person in one line in R

I have a data frame that looks like this:

ID  V1 V2  V3
1   1  2   3
1   2  3   4
1   3  4   5
2   3  4   5
3   4  5   6
3   2  3   4

I need to change the data frame so that all records belong to one person present on the same line for example:

ID V1 V2 V3 V1_2 V2_2 V3_2 V1_3 V2_3 V3_3
1  1  2  3  2     3    4    3    4    5
2  3  4  5
3  4  5  6  2     3    4  

Since each person has a different number of records, the new data frame will have a different length in each row. How can I achieve this?

+4
source share
1 answer

One easy way is to package reshape2, but you must add a secondary identifier.

### The next line creates a secondary ID variable
mydf$ID2 <- ave(mydf$ID, mydf$ID, FUN = seq_along)

library(reshape2)
dfL <- melt(mydf, id.vars=c("ID", "ID2"))
dcast(dfL, ID ~ variable + ID2)
#   ID V1_1 V1_2 V1_3 V2_1 V2_2 V2_3 V3_1 V3_2 V3_3
# 1  1    1    2    3    2    3    4    3    4    5
# 2  2    3   NA   NA    4   NA   NA    5   NA   NA
# 3  3    4    2   NA    5    3   NA    6    4   NA

"ID2", , R reshape. , .

reshape(mydf, direction = "wide", idvar="ID", timevar="ID2")
#   ID V1.1 V2.1 V3.1 V1.2 V2.2 V3.2 V1.3 V2.3 V3.3
# 1  1    1    2    3    2    3    4    3    4    5
# 4  2    3    4    5   NA   NA   NA   NA   NA   NA
# 5  3    4    5    6    2    3    4   NA   NA   NA
+6

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


All Articles