小编Dav*_*vid的帖子

Rcpp中的矩阵乘法

首先,我是一个新手用户,所以忘记我一般的无知.我正在寻找更快的替代R中的%*%运算符.虽然较旧的帖子建议使用RcppArmadillo,但我已经尝试了2个小时让RcppArmadillo工作没有成功.我总是遇到会产生'意外......'错误的词汇问题.我在Rcpp中找到了以下功能,我可以做的工作:

library(Rcpp)
func <- '
NumericMatrix mmult( NumericMatrix m , NumericMatrix v, bool  byrow=true )
{
  if( ! m.nrow() == v.nrow() ) stop("Non-conformable arrays") ;
  if( ! m.ncol() == v.ncol() ) stop("Non-conformable arrays") ;

  NumericMatrix out(m) ;

  for (int i = 0; i < m.nrow(); i++) 
  {
  for (int j = 0; j < m.ncol(); j++) 
  {
  out(i,j)=m(i,j) * v(i,j) ;
  }
  }
  return out ;
}
'
Run Code Online (Sandbox Code Playgroud)

但是,此函数执行逐元素乘法,并且不表现为%*%.有没有一种简单的方法来修改上面的代码来实现预期的结果?

编辑:

我已经提出了一个使用RcppEigen的函数,似乎超过%*%:

etest <- cxxfunction(signature(tm="NumericMatrix",
                           tm2="NumericMatrix"),
                 plugin="RcppEigen",
                 body="
NumericMatrix tm22(tm2);
NumericMatrix …
Run Code Online (Sandbox Code Playgroud)

c++ r rcpp

11
推荐指数
2
解决办法
4717
查看次数

沿行复制列的值

给出以下数据框:

df1 <- data.table( V1=c(0,0,0,0),V2=c(0,0,0,0),V3=c(0,2,0,2))
df1
   V1 V2 V3
1:  0  0  0
2:  0  0  2
3:  0  0  0
4:  0  0  2
Run Code Online (Sandbox Code Playgroud)

我试图在整行上复制V3的值,这样:

df2
   V1 V2 V3
1:  0  0  0
2:  2  2  2
3:  0  0  0
4:  2  2  2
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

提前谢谢了.

r data.table

4
推荐指数
1
解决办法
93
查看次数

按索引替换行

在以下示例中:

library(data.table)
df1 <- data.table("1A"=c(0,0,0,0),"1B"=c(4:3),"2A"=c(0,0,0,0), "2B"=c(4:3))
df2 <- data.table("1A"=c(0,0),"1B"=c(1:2),"2A"=c(0,0), "2B"=c(1:2))

df1
#    1A 1B 2A 2B
# 1:  0  4  0  4
# 2:  0  3  0  3
# 3:  0  4  0  4
# 4:  0  3  0  3

df2
#    1A 1B 2A 2B
# 1:  0  1  0  1
# 2:  0  2  0  2

indx = c(1,3)
indx
# [1] 1 3

df1[indx,] <- df2
df1
#    1A 1B 2A 2B
# 1:  0  1  0 …
Run Code Online (Sandbox Code Playgroud)

r data.table

3
推荐指数
1
解决办法
460
查看次数

撤消重塑为原始data.table格式

鉴于以下数据表描述了AT和BE国家汽车制造的生产投入:

DT <- data.table( Abb=c("AT", "AT", "BE", "BE"),input=c("iron", "glass", "iron", "glass"),AT_Car=c(5,5,0,5),BE_Car=c(0,3,2,2))

> DT
   Abb input AT_Car BE_Car
1:  AT  iron      5      0
2:  AT glass      5      3
3:  BE  iron      0      2
4:  BE glass      5      2
Run Code Online (Sandbox Code Playgroud)

我使用了reshape函数来计算一些东西:

DT2 <- reshape(DT,direction='wide',idvar='Abb', timevar='input')

> DT2
   Abb AT_Car.iron BE_Car.iron AT_Car.glass BE_Car.glass
1:  AT           5           0            5            3
2:  BE           0           2            5            2
Run Code Online (Sandbox Code Playgroud)

修改后,我需要将DT2转换回DT的原始格式.我怎样才能做到这一点?

先感谢您.

r reshape data.table

1
推荐指数
1
解决办法
265
查看次数

标签 统计

r ×4

data.table ×3

c++ ×1

rcpp ×1

reshape ×1