将几组列收集到新类别中

时间:2019-03-04 20:52:02

标签: r tidyverse

仍在学习R,我已经看过 Combine Multiple Columns Into Tidy DataGather multiple sets of columns  但不能完全回答我的问题。

我有这个数据集,需要将宽数据帧收集到长数据帧中。

year    City       electricity  water
2000    Boston          148.58  150.8
2001    Boston          189.41  170.34
2002    Boston          234.68  181.89
2003    Boston          272.14  186.43
2004    Boston          253.33  158.29
2000    Houston         111.73  159.11
2001    Houston         132.86  195.5
2002    Houston         164.54  223.02
2003    Houston         219.74  305.88
2004    Houston         234.13  291.35
2000    San Fransicso   170.74  165.74
2001    San Fransicso   205.14  199.14
2002    San Fransicso   223.33  123.33
2003    San Fransicso   311.17  411.17
2004    San Fransicso   293.01  213.01

最后我要结束:

usage_data <- data.frame(stringsAsFactors=FALSE,
year = c("2000", "2001", "2002", "2003", "2004"),
Bn_elec = c(148.58, 189.41, 234.68, 272.14, 253.33),
Bn_water = c(150.8, 170.34, 181.89, 186.43, 158.29),
Hn_elec = c(111.73, 132.86, 164.54, 219.74, 234.13),
Hn_water = c(159.11, 195.5, 223.02, 305.88, 291.35),
SF_elec = c(170.74, 205.14, 223.33, 311.17, 293.01),
SF_water = c(165.74, 199.14, 123.33, 411.17, 213.01))

用于复制数据集的代码:

foreach($bodyDivs[0]->childNodes as $divChild) {
    $dom->getElementsByTagName('body')[0]->appendChild($divChild);
}

1 个答案:

答案 0 :(得分:1)

我们flutter.jar变成“ long”,gather的“ key”列变成“ two”,然后separate

spread