简体   繁体   English

R:比祝福快吗?

[英]R: anything faster than sapply?

Suppose that I have a matrix for 7 items with 5 options, and a vector for 10 people. 假设我有一个包含5个选项的7个项目的矩阵,以及一个10个人的矢量。 What I need to calculate is to multiply each item value for each option with each person value. 我需要计算的是将每个选项的每个项目值乘以每个人的值。 I was able to do it by using sapply , resulting in 5 different matrices. 我能够通过使用sapply来实现它,从而产生5种不同的矩阵。 But, actually as my data is pretty huge, I was wondering if there is any other way faster than sapply . 但是,实际上因为我的数据非常庞大,我想知道是否还有其他任何方式比sapply更快。 Below is the example. 以下是示例。

set.seed(10)
person<-round(runif(10,-2,2),3)
[1]  0.030 -0.773 -0.292  0.772 -1.659 -1.098 -0.902 -0.911  0.463 -0.281
set.seed(10)
item<-round(matrix(runif(35,0,1),nrow=7),3)
      [,1]  [,2]  [,3]  [,4]  [,5]
[1,] 0.507 0.272 0.358 0.615 0.771
[2,] 0.307 0.616 0.429 0.775 0.356
[3,] 0.427 0.430 0.052 0.356 0.536
[4,] 0.693 0.652 0.264 0.406 0.093
[5,] 0.085 0.568 0.399 0.707 0.170
[6,] 0.225 0.114 0.836 0.838 0.900
[7,] 0.275 0.596 0.865 0.240 0.423

## multiplication
m1<-t(sapply(person, FUN=function(x) item[,1]* x))
m2<-t(sapply(person, FUN=function(x) item[,2]* x))
m3<-t(sapply(person, FUN=function(x) item[,3]* x))
m4<-t(sapply(person, FUN=function(x) item[,4]* x))
m5<-t(sapply(person, FUN=function(x) item[,5]* x))

You are doing this 你这样做

A <- outer(person,item)

As shown 如图所示

> all.equal(A[,,1],m1)
[1] TRUE
> all.equal(A[,,2],m2)
[1] TRUE
> all.equal(A[,,3],m3)
[1] TRUE
> all.equal(A[,,4],m4)
[1] TRUE
> all.equal(A[,,5],m5)
[1] TRUE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM