bvowe
bvowe

Reputation: 3384

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'

Upvotes: 0

Views: 75

Answers (4)

akrun
akrun

Reputation: 887541

We can use pivot_wider from tidyr

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

Upvotes: 1

Ian Campbell
Ian Campbell

Reputation: 24838

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

Upvotes: 2

Daniel O
Daniel O

Reputation: 4358

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]
}

Upvotes: 1

altfi_SU
altfi_SU

Reputation: 588

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

Upvotes: 1

Related Questions