Spread R Data.Table

问题描述 投票:0回答:1
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))

我有'data1',并希望获得'data2',在此您将组从'data1'转换为'A'和'B',然后最后添加'Combine',将'A'和'B'相加。

r data.table
1个回答
0
投票

您可以做

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

0
投票

在基本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]
}
© www.soinside.com 2019 - 2024. All rights reserved.