在R中,有一种非常方便的方式可以使用
{reshape2}
包中的dcast
函数将“长”数据转换为“宽”数据,并应用一个函数(如计算出现次数)。我想在javascript中使用类似的转换方法。以下是一个R示例(附带样本数据):library(reshape2)
data.long = read.table("so_question2.csv", sep = "\t")
head(data.long)
# This is how a first few rows of the original data look like:
# dpt sem
# 15 Dpt.4 2014.1
# 16 Dpt.4 2014.1
# 17 Dpt.4 2014.1
# 18 Dpt.4 2014.1
# 19 Dpt.4 2014.1
# 20 Dpt.4 2014.1
data.wide = dcast(data, sem ~ dpt, length)
head(data.wide)
# This is how it looks like after the transformation; there are counts in columns now
# sem Dpt.1 Dpt.2 Dpt.3 Dpt.4
# 1 2012.1 0 0 0 8
# 2 2012.2 3 6 0 21
# 3 2013.1 3 4 0 29
# 4 2013.2 5 1 2 39
# 5 2014.1 5 3 7 39
为什么需要这个功能:我正在学习使用Google Charts,并希望能够在从电子表格中导入数据后对其进行转换。我知道可以在电子表格本身中进行转换;但是在电子表格中添加大量公式会很不方便。我更希望每个图表都能在其自己的脚本中进行转换。