向量化R中的哪些语句

问题描述 投票:2回答:1

我目前有以下代码。

names <- c("Red","Green","Blue","Orange","Yellow")
aMatrix <- matrix(data=0,nrow=5,ncol=5)
df <- data.frame(matrix(nrow=5,ncol=2))
colnames(df)=c("Number","name")    
selectedRows=sample(1:5, 5)
samples=sample(1:5, 5)
for (i in 1:5){
    df[i,"Number"]=i
    df[i,"name"]=names[samples[i]]
}
for (i in 1:5){
    aMatrix[i,which(names==df[selectedRows[i],"name"])]=1
}

有没有办法矢量化最后一个循环,以便它运行得更快?

r
1个回答
2
投票

可以通过使用match创建列索引来完成,cbind使用列索引创建行索引以从aMatrix中提取值并将其分配给1

aMatrix2 <- aMatrix # before the assignment in OP's code
aMatrix2[cbind(seq_len(nrow(aMatrix)), match(df$name[selectedRows], names))] <- 1

-检查

identical(aMatrix, aMatrix2)
#[1] TRUE
© www.soinside.com 2019 - 2024. All rights reserved.