通过创建新变量来重塑

时间:2018-11-16 03:33:58

标签: r

如何通过在下面的数据集中添加另一个名为month的变量来转换数据

ID   Com    Lac   Nov(PM)    Nov(TM)  Dec(PM) Dec(TM)
1     A      E      12        11        28       29
2     B      F      2         13        26       44
3     C      G      7         15        18       37
4     D      H      4         10        22       22

上方是需要像下面这样转换的数据框

ID   Com    Lac   Month    PM     TM
1    A       E     Nov      12    11
1    A       E     Dec      28    29
2    B       F     Nov      2     13
2    B       F     Dec      26    44
3    C       G     Nov      7     15
3    C       G     Dec      18    37
4    D       H     Nov      4     10
4    D       H     Dec      22    22

数据:

df1 <- structure(list(ID = 1:4, Com = c("A", "B", "C", "D"), Lac = c("E", 
 "F", "G", "H"), `Nov(PM)` = c(12L, 2L, 7L, 4L), `Nov(TM)` = c(11L, 
13L, 15L, 10L), `Dec(PM)` = c(28L, 26L, 18L, 22L), `Dec(TM)` = c(29L, 
44L, 37L, 22L)), class = "data.frame", row.names = c(NA, -4L))

2 个答案:

答案 0 :(得分:3)

这是Update friends set email= (case when id=1 then 'jane@abc.com' when id=2 then 'melissa@abc.com' when id=3 then 'andrew@abc.com' end) 的一个选项。我们 urlLauncher(String url) async { if (await canLaunch(url)) { await launch(url, forceWebView: true); } else { throw 'Could not launch $url'; } } 列中的'Nov(PM)tidyverse变成'long'格式,然后使用gather,将'key'列分为'Month'和另一列,最后{ {1}}为“宽”格式

to 'Dec(TM)

数据

extract

答案 1 :(得分:1)

所有功能中最邪恶,最被鄙视的reshape很好地处理了这个问题。只要您将名称从"Time(Variable)"旋转到"Variable_Time",它就会一次完成所有操作:

names(df1) <- gsub("(.+?)\\((.+?)\\)", "\\2_\\1", names(df1))
reshape(df1, idvar=c("ID","Com","Lac"), varying=4:7,
        direction="long", sep="_", timevar="Month")

#          ID Com Lac Month PM TM
#1.A.E.Nov  1   A   E   Nov 12 11
#2.B.F.Nov  2   B   F   Nov  2 13
#3.C.G.Nov  3   C   G   Nov  7 15
#4.D.H.Nov  4   D   H   Nov  4 10
#1.A.E.Dec  1   A   E   Dec 28 29
#2.B.F.Dec  2   B   F   Dec 26 44
#3.C.G.Dec  3   C   G   Dec 18 37
#4.D.H.Dec  4   D   H   Dec 22 22