说我有以下数据框:
ID<-c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3, 4,4,4,4,4,5,5,5,5,5) Score<- sample(1:20, 25, replace=TRUE) days<-rep(c("Mon", "Tue", "Wed", "Thu", "Fri"), times=5) t<-cbind(ID, Score, days)
我想重塑它,以便新列是ID和实际工作日名称(意思是6列),并且分数值根据其ID和日期名称分配.像这样的东西:
我发现重塑包可能会这样做.尝试(融化和演员),但它没有产生我想要的结果,但在这篇文章中的内容:一列的熔化数据
使用内置reshape
命令的基本R解决方案.
set.seed(12345) t <- data.frame(id = c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5), score = sample(x = 1:20,size = 25,replace = TRUE), days = rep(x = c("Mon","Tue","Wed","Thu","Fri"),times = 5)) t.wide <- reshape(data = t, v.names = "score", timevar = "days", idvar = "id", direction = "wide") names(t.wide) <- gsub(pattern = "score.",replacement = "",x = names(t.wide),fixed = TRUE) t.wide id Mon Tue Wed Thu Fri 1 1 15 18 16 18 10 6 2 4 7 11 15 20 11 3 1 4 15 1 8 16 4 10 8 9 4 20 21 5 10 7 20 15 13
您可以使用reshape2执行此操作,但您需要data.frame
执行此操作.使用cbind生成一个矩阵.(并且在这种情况下将所有数值变量转换为字符,因为矩阵只能包含一种数据类型).
我已经改变了你的代码来生成一个数据帧,它已经是长格式(每个观察一行).
set.seed(123) ID<-c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3, 4,4,4,4,4,5,5,5,5,5) Score<- sample(1:20, 25, replace=TRUE) days<-rep(c("Mon", "Tue", "Wed", "Thu", "Fri"), times=5) dat<-data.frame(ID, Score, days)
reshape2
然后将其更改为广泛使用非常简单:
library(reshape2) res <- dcast(ID~days,value.var="Score",data=dat) > res ID Fri Mon Thu Tue Wed 1 1 16 3 2 12 6 2 2 19 13 12 7 19 3 3 19 19 17 8 15 4 4 15 3 8 1 20 5 5 3 11 18 8 15