使用值填充data.frame。如何加快这个过程?

时间:2014-10-27 13:03:08

标签: r

我目前正在尝试使用另一个data.frame中的值填充空data.frame。首先,我使用相应的维度初始化一个空的data.frame然后我使用for循环用这些值填充这个data.frame,这些值包含在另一个data.frame中。有没有办法使用apply-type-function来加速这个过程?

提前致谢, BenR

更新2:修复示例。

set.seed(8760)
k <- c(rep(1:4, each = 6))
i <- paste(rep(LETTERS[1:6], times=4))
value <- sample(1:10000, 24)

input <- data.frame(k, i, value)

u_n <- unique(input$i)
id <- unique(input$k)

#' doConversion
#' 
#' Converts a dataset from original gdx version to more readable version.
#' 
#' @param x dataframe containing results of reporting.gms (sum_generation_parameter).
#' @return dataframe with EU-aggregated generation
#' @author BenR
doConversion <- function(x){
  stopifnot(class(x) %in% c("data.frame","matrix") &
              names(x) == c("k","i","value"))

  # get technology name and temporal id
  u_n <- unique(x$i)
  id <- unique(x$k)

  # initialise data.frame containing all zeros and the right names
  nodata <- data.frame(setNames(replicate(length(u_n),numeric(length(id)), simplify = F), u_n))
  data <- cbind(id, nodata)

  # assign values to particular entries of the data.frame
  for (i in colnames(data[, 2:ncol(data)])){
    for (j in id){
      if(length(rownames(x[which(x$i == i & x$k == j) , ])==0)){
        help <- x[which(x$i == i & x$k == j), "value"]
        data[which(data$id == j) ,i ] <- help
      }
    }
  }
  return(data)
}

r <- doConversion(input)

1 个答案:

答案 0 :(得分:1)

你的职能:

doConversion(input)
#  id    A    B    C    D    E    F
#1  1 6947 6344 6291 2182 5430 9555
#2  2 2758 4375 7649 3096 8325 1109
#3  3 6073  168 2265 8739 6293 9003
#4  4 6278 1994 8597  332 2716 6504

使用reshape2包:

library(reshape2)
dcast(input, k ~ i)
#  k    A    B    C    D    E    F
#1 1 6947 6344 6291 2182 5430 9555
#2 2 2758 4375 7649 3096 8325 1109
#3 3 6073  168 2265 8739 6293 9003
#4 4 6278 1994 8597  332 2716 6504

但是,正如我在评论中所说,输入的长格式通常更适合R中的数据处理。