我需要找到行数最小的(+60)
相对较大data.frame(~250,000 x 3)(或者我可以等效地工作xts).
set.seed(1000)
my.df <- sample(1:5, 250000*3, replace=TRUE)
dim(my.df) <- c(250000,3)
my.df <- as.data.frame(my.df)
names(my.df) <- c("A", "B", "C")
Run Code Online (Sandbox Code Playgroud)
数据框my.df看起来像这样
> head(my.df)
A B C
1 2 5 2
2 4 5 5
3 1 5 3
4 4 4 3
5 3 5 5
6 1 5 3
Run Code Online (Sandbox Code Playgroud)
我试过了
require(data.table)
my.dt <- as.data.table(my.df)
my.dt[, row.min:=0] # without this: "Attempt to add new column(s) and set subset of rows at the same …Run Code Online (Sandbox Code Playgroud) 我通常使用一个简短的 Rcpp 函数,该函数将一个矩阵作为输入,其中每行包含 K 个总和为 1 的概率。然后该函数为每一行随机采样 1 到 K 之间的整数,对应于提供的概率。这是函数:
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadilloExtensions/sample.h>
using namespace Rcpp;
// [[Rcpp::export]]
IntegerVector sample_matrix(NumericMatrix x, IntegerVector choice_set) {
int n = x.nrow();
IntegerVector result(n);
for ( int i = 0; i < n; ++i ) {
result[i] = RcppArmadillo::sample(choice_set, 1, false, x(i, _))[0];
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
我最近更新了 R 和所有软件包。现在我不能再编译这个函数了。我不清楚原因。跑步
library(Rcpp)
library(RcppArmadillo)
Rcpp::sourceCpp("sample_matrix.cpp")
Run Code Online (Sandbox Code Playgroud)
引发以下错误:
error: call of overloaded 'sample(Rcpp::IntegerVector&, int, bool, Rcpp::Matrix<14>::Row)' is ambiguous
Run Code Online (Sandbox Code Playgroud)
这基本上告诉我,我的电话RcppArmadillo::sample()是模棱两可的。任何人都可以启发我为什么会这样吗?
我需要在给定具有行方式结果概率的矩阵的情况下对结果变量进行采样.
set.seed(1010) #reproducibility
#create a matrix of probabilities
#three possible outcomes, 10.000 cases
probabilities <- matrix(runif(10000*3),nrow=10000,ncol=3)
probabilities <- probabilities / Matrix::rowSums(probabilities)
Run Code Online (Sandbox Code Playgroud)
我能想出的最快方法是apply()和sample()的组合.
#row-wise sampling using these probabilities
classification <- apply(probabilities, 1, function(x) sample(1:3, 1, prob = x))
Run Code Online (Sandbox Code Playgroud)
但是,在我正在做的事情中,这是计算瓶颈.您是否知道如何加快此代码速度/如何更有效地进行采样?
谢谢!