我有一个 Dataframe 如下:
df <- data.frame(code=c("A1","A2","A3","A4","B1","B2","B3","B4"),
pcode = c("el","el","ng","el","ng","el","el","el"),
psaved=c(10,10,10,10,10,10,10,10),
pcost=c(20,20,30,25,34,25,30,20),
scode = c("e1","e2","e2","e2","e2","e2","e3","e3"),
ssaved=c(10,10,10,10,10,10,10,10),
scost=c(20,20,30,25,34,25,30,20),
tcode = c("e2","e3","e1","e1","e3","e3","e2","e1"),
tsaved=c(10,10,10,10,10,10,10,10),
tcost=c(20,20,30,25,34,25,30,20))
我希望扩展 Dataframe ,使pcode、scode和tcode列中的内容成为单独的列,它们对应的saved和cost值位于各自的单元格中,结果应该如下所示:
我尝试执行pivot_wideer来帮助我获得更宽的 Dataframe ,其中包含pcode、scode、tcode中的变量,以便与它们各自的成本和保存值保持一致
1条答案
按热度按时间4sup72z81#
一种选择是分两步完成,首先使用
pivot_longer
,然后执行pivot_wider
: