【发布时间】:2020-04-24 07:00:54
【问题描述】:
我想要做的是重新排序数据在列中的数据,但保留其余变量
c1<- c("ID","Location", "Year","Gender", "MoneySpent", "MoneyWithCreditCard")
c2<- c(1,"EEUU",2007,"M",1500,400)
c3<- c(1,"EEUU",2008,"M",3900,0)
c4<- c(1,"EEUU",2009,"M",0,100)
c5<- c(2,"Germany",2007,"F",0,1000)
c6<- c(2,"Germany",2008,"F",4000,500)
c7<- c(2,"Germany",2009,"F",700,0)
c8<- c(2,"Germany",2010,"F",0,50)
Df<-data.frame(rbind(c2,c3,c4,c5,c6,c7,c8))
colnames(Df)<-c1
# ID Location Year Gender MoneySpent MoneyWithCreditCard TypeofHome
#c2 1 EEUU 2007 M 1500 400 House
#c3 1 EEUU 2008 M 3900 0 House
#c4 1 EEUU 2009 M 0 100 House
#c5 2 Germany 2007 F 0 1000 Department
#c6 2 Germany 2008 F 4000 500 Department
#c7 2 Germany 2009 F 700 0 Department
#c8 2 Germany 2010 F 0 50 Department
我需要的结果是这个:
# ID Location Gender TypeofHome MS.2007 MS.2008 MS.2009 MS.2010 MWC.2007 MWC.2008 MWC.2009 MWC.2010
# 1 EEUU M House 1500 3900 0 NA 400 0 100 NA
# 2 Germany F Department 0 4000 700 0 1000 500 0 50
哪一个是更好的解决方案?谢谢顺便说一句!
【问题讨论】:
-
您能否检查您的
rbind代码,因为它与您显示的不同 -
检查! @akrun
-
我认为更新中的列名将是
MoneyWithCreditCard而不是CreditCard。我更新了你的帖子 -
"哪一个是更好的解决方案?"哪一个?您尝试过什么,其他长到宽的重塑帖子没有奏效怎么办?我会看看新的
tidyr::pivot_wider,它采用多个值列 -
使用
data.table:library(data.table); setDT(Df); dcast(Df, ID + Location + Gender ~ Year, value.var = c("MoneySpent", "MoneyWithCreditCard"))