在数据帧上应用 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,成本$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
看看它是否有效
相关文章:
- 试图在visual studio上用C++创建一个桌面应用程序
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- c++r值引用应用于函数指针
- 在C应用程序中运行C++(带有STL)函数
- 使用VerQueryValue检索应用程序的文件描述
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 如何使用Rcpp将R函数转换为C++函数
- rcpp函数中的清理时间很长
- 使用调试/崩溃报告将应用程序部署到客户端
- C++控制台应用程序阻止退出
- 码头化的C++应用程序是否向后兼容早期的内核版本
- 将应用程序从32位移植到64位时出现问题
- 有没有任务栏API可以立即应用注册表更改
- 如何改变c++应用程序的视觉效果
- WM_CTLCOLORSTATIC从未在WIN32应用程序中触发
- PC中的程序和PHONE中的本机描述应用程序之间的数据连接
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 示例外壳应用程序显示的 V8 "segmentation fault (core dumped)"错误
- 在数据帧上应用 Rcpp
- 在Rcpp中实现应用功能