有没有比从长格式转换到宽格式转换更好的性能解决方案?

时间:2017-02-10 11:01:42

标签: r performance dataframe reshape

我有一小段代码可以将数据帧从long转换为宽。

library(reshape2)
mydata <- structure(list(issn = c("1980-4814", "1945-3116", "1681-4835", "1367-0751", "1516-6104", "1359-7566", "2319-0795", "1390-6615", "1808-8023", "1746-4269", "1852-2181", "0022-4596", "1808-2386", "0254-6051", "1981-3686", "1077-2618", "1809-3957", "2179-5746", "0147-6513", "1070-5503"), periodico = c("ABCustos (", "Journal of", "The Electr", "Logic Jour", "DIREITO, E", "REGIONAL &", "REVISTA FÓ", "UMBRAL: RE", "Segurança ", "Journal of", "Augm Domus", "Journal of", "BBR. Brazi", "Jinshu Rèc", "Revista Br", "IEEE Indus", "Revista SO", "Biota Amaz", "Ecotoxicol", "Internatio"), qualis = c("B4", "B3", "B2", "B2", "A1", "B5", "B5", "C ", "B5", "B3", "B3", "A1", "B4", "B3", "B5", "A2", "C ", "B3", "A2", "B1"), area = c(1L, 1L, 1L, 2L, 3L, 3L, 3L, 3L, 4L, 5L, 6L, 6L, 7L, 7L, 7L, 8L, 8L, 9L, 9L, 9L)), .Names = c("issn", "periodico", "qualis", "area"), row.names = c(1L, 501L, 1001L, 1501L, 2001L, 2501L, 3001L, 3501L, 4001L, 4501L, 5001L, 5501L, 6001L, 6501L, 7001L, 7501L, 8001L, 8501L, 9001L, 9501L), class = "data.frame")

reshape(mydata, direction = "wide", 
        idvar = c("issn", "periodico"), 
        timevar = "area")

数据 enter image description here

,结果是

enter image description here

没问题,只是我想要,但随着数据框增长超过2000条记录,它变得非常慢。

我只有10个区域要映射到列,但超过10,000个区域。

我正在寻找更快的方法来实现相同的结果。

由于

2 个答案:

答案 0 :(得分:2)

对于重塑问题,来自dcast的{​​{1}}已经过高度优化,效率非常高,应该比目前可用的任何软件包更快

data.table

答案 1 :(得分:1)

您可以使用dplyrtidyr

library(dplyr)
library(tidyr)
mydata %>% 
  mutate(area = paste('qualis',area,sep=".")) %>% 
  spread(area, qualis)