简体   繁体   中英

Spread R Data.Table

data1=data.frame("Grade"=c(1,2,3,1,2,3),
"Group"=c(A,A,A,B,B,B),
"Score"=c(5,7,10,7,7,8))

data2=data.frame("Grade"=c(1,2,3),
"Combine"=c(12,14,18),
"A"=c(5,7,10),
"B"=c(7,7,8))

I have 'data1' and wish for 'data2' where you transpose Group from 'data1' into 'A' and 'B' and then finally add 'Combine' which sums 'A' and 'B'

You can do

library(tidyverse)

data1 %>%
  spread(Group, Score) %>%
  mutate(Combine = A+B)

  Grade  A B Combine
1     1  5 7      12
2     2  7 7      14
3     3 10 8      18

in Base R

data2 <- data.frame("Grade" = 1:3)

grade.locations <- lapply(1:3,grep,data1$Grade)
for(i in 1:3){
  data2$Combine[i] <- sum(data1[grade.locations[[i]],3])
  data2$A[i] <- data1[grade.locations[[i]][1],3]
  data2$B[i] <- data1[grade.locations[[i]][2],3]
}

You tagged this with data.table, so here's a data.table approach.

library(data.table)
data1 <- as.data.table(data1)
data2 <- dcast(data1,Grade ~ Group)
data2[,Combine := A + B]
data2

   Grade  A B Combine
1:     1  5 7      12
2:     2  7 7      14
3:     3 10 8      18

We can use pivot_wider from tidyr

library(dplyr)
library(tidyr)
data1 %>%
   pivot_wider(names_from = Group, values_from = Score) %>%
   mutate(Combine = A + B)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM