在数据帧上应用 Rcpp

Applying Rcpp on a dataframe

本文关键字:Rcpp 应用 数据帧      更新时间:2023-10-16

我是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,成本$303[1]=6

最终数据帧应如下所示 - 已创建示例输出

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

看看它是否有效