gpt4 book ai didi

R - 用 apply 系列中的函数替换双循环

转载 作者:行者123 更新时间:2023-12-05 01:10:06 24 4
gpt4 key购买 nike

我有这些循环:

xall = data.frame()
for (k in 1:nrow(VectClasses))
{
for (i in 1:nrow(VectIndVar))
{
xall[i,k] = sum(VectClasses[k,] == VectIndVar[i,])
}
}

数据:

VectClasses = 包含每个类特征的数据框

VectIndVar = 包含数据库每条记录的数据框

这两个 for 循环工作并给出了我可以使用的输出,但是,它花费的时间太长,因此我需要 apply 系列

我正在寻找的输出是这样的:

    V1 V2 V3 V4
1 3 3 2 2
2 2 2 1 1
3 3 4 3 3
4 3 4 3 3
5 4 4 3 3
6 3 2 3 3

我尝试使用:

xball = data.frame()
xball = sapply(xball, function (i,k){
sum(VectClasses[k,] == VectIndVar[i,])})

xcall = data.frame()
xcall = lapply(xcall, function (i, k){sum(VectClasses[k,] == VectIndVar[i,]} )

但似乎都没有填充数据框

可重现数据(缩短):

VectIndVar <- data.frame(a=sample(letters[1:5], 100, rep=T), b=floor(runif(100)*25), 
c = sample(c(1:5), 100, rep=T),
d=sample(c(1:2), 100, rep=T))

和:

> K1 = 4
VectClasses= VectIndVar [sample(1:nrow(VectIndVar ), K1, replace=FALSE), ]

你能帮帮我吗?

最佳答案

我会使用 outer 而不是 *apply:

res <- outer( 
1:nrow(VectIndVar),
1:nrow(VectClasses),
Vectorize(function(i,k) sum(VectIndVar[i,-1]==VectClasses[k,-1]))
)

(感谢 this Q&A 澄清需要Vectorize。)

这给出了

> head(res) # with set.seed(1) before creating the data
[,1] [,2] [,3] [,4]
[1,] 1 1 2 1
[2,] 0 0 1 0
[3,] 0 0 0 0
[4,] 0 0 1 0
[5,] 1 0 0 1
[6,] 1 1 1 1

至于速度,我建议使用矩阵而不是 data.frames:

cmat <- as.matrix(VectClasses[-1]); rownames(cmat)<-VectClasses$a
imat <- as.matrix(VectIndVar[-1]); rownames(imat)<-VectIndVar$a

关于R - 用 apply 系列中的函数替换双循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30460532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com