R 试图一次使数据范围为4列
我正在努力使我的数据比现在更广泛。我尝试使用spread,但我想一次传播4个变量。示例数据集是:R 试图一次使数据范围为4列,r,dplyr,spread,R,Dplyr,Spread,我正在努力使我的数据比现在更广泛。我尝试使用spread,但我想一次传播4个变量。示例数据集是: df <- data.frame(Year <- c("2017","2018"), ID <- c(1,1), Score <- c("21","32"), Score2 <- c("24","20"),
df <- data.frame(Year <- c("2017","2018"),
ID <- c(1,1),
Score <- c("21","32"),
Score2 <- c("24","20"),
Score3 <- c("33", "26"),
Score4 <- c("25","32"))
Year ID Score Score2 Score3 Score4
1 2017 1 21 24 33 25
2 2018 1 32 20 26 32
“第二年”栏不是完全必要的,但我想在2017年和2018年之间找到一些破译的方法
任何帮助或指导都将不胜感激!谢谢 我们可以从
数据表中使用dcast
library(data.table)
dcast(setDT(df), ID ~ rowid(ID), value.var = setdiff(names(df), 'ID'),
sep="")[, ID := NULL][]
# Year1 Year2 Score1 Score2 Score21 Score22 Score31 Score32 Score41 Score42
#1: 2017 2018 21 32 24 20 33 26 25 32
或者使用从base R
reshape(transform(df, tvar = seq_len(nrow(df))),
idvar = 'ID', direction = 'wide', timevar = 'tvar')[-1]
# Year.1 Score.1 Score2.1 Score3.1 Score4.1 Year.2 Score.2 Score2.2 Score3.2 Score4.2
#1 2017 21 24 33 25 2018 32 20 26 32
数据
df另一种方法可能是
库(tidyverse)
库(splitstackshape)
df%>%
分组依据(ID)%>%
汇总所有(funs(toString))%>%
cSplit(名称(.)[-1],“,”)
输出为:
ID Year_1 Year_2 Score_1 Score_2 Score2_1 Score2_2 Score3_1 Score3_2 Score4_1 Score4_2
1: 1 2017 2018 21 32 24 20 33 26 25 32
df <- data.frame(Year = c("2017","2018"),
ID = c(1,1),
Score = c("21","32"),
Score2 = c("24","20"),
Score3 = c("33", "26"),
Score4 = c("25","32"))
样本数据:
ID Year_1 Year_2 Score_1 Score_2 Score2_1 Score2_2 Score3_1 Score3_2 Score4_1 Score4_2
1: 1 2017 2018 21 32 24 20 33 26 25 32
df <- data.frame(Year = c("2017","2018"),
ID = c(1,1),
Score = c("21","32"),
Score2 = c("24","20"),
Score3 = c("33", "26"),
Score4 = c("25","32"))
df是抱歉,我没有添加ID,假设有一个ID列,两行的ID都是“1”