I have a dataframe:
df1<-data.frame(ID=c(1,2,2,3,3,3,4),
V1=c(1,2,3,4,5,6,7),
V2=c(8,9,10,11,12,13,14),
V3=c(15,16,17,18,19,20,21))
> df1
ID V1 V2 V3
1 1 1 8 15
2 2 2 9 16
3 2 3 10 17
4 3 4 11 18
5 3 5 12 19
6 3 6 13 20
7 4 7 14 21
I would like to combine rows when the rows have the same ID
, but expand new columns because the rows with same ID
have differnet values in each of the variable. I would like the final table to be like:
> df1
ID V1.1 V1.2 V1.3 V2.1 V2.2 V2.3 V3.1 V3.2 V3.3
1 1 1 NA NA 8 NA NA 15 NA NA
2 2 2 3 NA 9 10 NA 16 17 NA
3 3 4 5 6 11 12 13 18 19 20
4 4 7 NA NA 14 NA NA 21 NA NA
Is there any way to do that in r?
We can use pivot_wider
library(dplyr)
library(tidyr)
library(data.table)
df1 %>%
mutate(nm1 = rowid(ID)) %>%
pivot_wider(names_from = nm1, values_from = c(V1, V2, V3), names_sep=".")
-output
# A tibble: 4 x 10
# ID V1.1 V1.2 V1.3 V2.1 V2.2 V2.3 V3.1 V3.2 V3.3
# <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 1 1 NA NA 8 NA NA 15 NA NA
#2 2 2 3 NA 9 10 NA 16 17 NA
#3 3 4 5 6 11 12 13 18 19 20
#4 4 7 NA NA 14 NA NA 21 NA NA
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.