I'm trying to optimize a loop in r that counts the number of string matches of each element in a vector regarding each row in a data frame. In small datasets it works pretty good (~15 min; 11 columns, 914 rows). However, it takes days for running in huge datasets (914 columns, 18.000 rows). Here's my extremely basic loop:
for (j in 1: dim(pddbnh)[1]){
for (i in 1:dim(pidf)[1]){
richa[i,j] <- length(pidf[i,][pidf[i,] == row.names(pddbnh)[j] ])
}
}
I'm wondering if anyone knows how to optimize this loop using other approach (e.g. vectorization). Any solution would be much appreciated!
UPDATE Here's a small dataset. That's the fastest one
df<-data.frame(replicate(10,sample(c("sp1", "sp2"),10,rep=TRUE)))
vec<-c("sp1", "sp2")
richa <- data.frame()
for (j in 1:length(vec)){
for (i in 1:dim(df)[1]){
richa[i,j] <- length(df[i,][df[i,] == vec[j] ])
}
}
[to process[ pidf[i,] == row.names(pddbnh)[j] ]would seem doomed to failure. The result of that argument will be either 0 or 1 after coercion (so errors regarding replacement having length zero should appear). Maybe you should explain what it is that you are actually attempting. - IRTFM