简体   繁体   English

如何在R中使用Apply函数删除循环

[英]How to use apply function in R to remove loop

I have a matrix 我有一个矩阵

A <- matrix(c(1,2,1,2,4,4,6,7,6),nrow=3,ncol=3)

So basically I am replacing each element with the frequency of it occurring as seen in the corresponding column and taking the product of all the elements in the row. 因此,基本上,我用在相应列中看到的出现频率替换了每个元素,并获取行中所有元素的乘积。

My approach 我的方法

fr <- c(paste("fr", 1:97, sep = ""))
for(i in 1:3){assign(fr[i],table(A[,i]))}
prob=matrix(c(rep(1,3)),3, byrow = T)
for (i in 1:3)
{
   for (j in 1:3)
{
    prob[i]<-prob[i]*get(fr[j])[as.character(A[i,j])]
}
}

Is there any way to solve this without writing loops, using the matrix structure? 有没有办法使用矩阵结构来解决此问题而无需编写循环?

I think we can use the apply 我认为我们可以使用apply

I am using R language 我正在使用R语言

Your matrix: 您的矩阵:

A <- matrix(c(1,2,3,4,5,6,1,4,6), ncol=3, byrow=T)

Apply colwise a function that calculates the probability table: 逐个应用一个计算概率表的函数:

B <- apply(A, 2, function(x) prop.table(table(x))[as.character(x)])
#           [,1]      [,2]      [,3]
# [1,] 0.6666667 0.3333333 0.3333333
# [2,] 0.3333333 0.3333333 0.6666667
# [3,] 0.6666667 0.3333333 0.6666667

Calculate the product rowwise: 按行计算乘积:

apply(B, 1, prod)
#[1] 0.07407407 0.07407407 0.14814815

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

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