在数据帧上应用 Rcpp

Applying Rcpp on a dataframe

我是 C++ 的新手,正在探索通过 Rcpp 包在 R 上进行更快计算的可能性。实际数据框包含超过 200 万行,而且速度很慢。

现有数据框

主数据框

df<-data.frame(z = c("a","b","c"), a = c(303,403,503), b = c(203,103,803), c = c(903,803,703))

成本数据框

cost <- data.frame("103" = 4, "203" = 5, "303" = 6, "403" = 7, "503" = 8, "603" = 9, "703" = 10, "803" = 11, "903" = 12)

colnames(cost) <- c("103", "203", "303", "403", "503", "603", "703", "803", "903")

步骤

df 包含 z,它是具有 a、b 和 c 水平的分类变量。我从另一个数据帧进行了合并操作,将 a、b、c 带入具有特定编号的 df。

第一步是将 z 中的每一行与列名(a、b 或 c)匹配并创建一个名为 'type' 的新列并复制相应的数字。

所以第一行应该是,

df$z[1] = "a"
df$type[1]= 303

现在它必须将 df$type 与另一个名为 'cost' 的数据框中的列名匹配并创建 df$cost。成本数据框包含列名作为数字,例如“103”、“203”等

对于我们的示例,df$cost[1] = 6。它匹配 df$type[1] = 303 和 cost$303[1]=6

最终 Dataframe 应如下所示 - 创建了示例输出

df1 <- data.frame(z = c("a","b","c"), type = c("303", "103", "703"), cost = c(6,4,10))

一个可能的解决方案,不是很优雅,但可以完成工作:

library(reshape2)

tmp <- cbind(cost,melt(df)) # create a unique data frame

row.idx <- which(tmp$z==tmp$variable) # row index of matching values
col.val <- match(as.character(tmp$value[row.idx]), names(tmp) ) # find corresponding values in the column names
# now put all together
df2 <- data.frame('z'=unique(df$z),
                  'type' = tmp$value[row.idx],
                  'cost' =  as.numeric(tmp[1,col.val]) )

输出:

> df2 
  z type cost
1 a  303    6
2 b  103    4
3 c  703   10

看看是否有效