dimanche 26 juillet 2020

Loop over multiple matrices to log normalize values using ifelse in R [duplicate]

I'm working on a couple sparse matrices and I try to log-normalize numerical values for those > 0 while retaining those 0 values to just 0. I though it would be more convenient if I just write a for loop to loop over a list of matrices instead of calling ifelse(matrix1 > 0, log(matrix1), 0) multiple times. Here's what I got, but I can't get my code to work. I've referenced this earlier post though.

df1 <- readRDS(url("https://www.dropbox.com/s/4myqq6aqxqys4y2/comtrade2000.rds?dl=1"))
df2 <- readRDS(url("https://www.dropbox.com/s/24mthn9xtpxqwuo/comtrade2001.rds?dl=1"))
df3 <- readRDS(url("https://www.dropbox.com/s/nnywm8ysquqd5nf/comtrade2002.rds?dl=1"))

lt <- list(df1, df2, df3)

for (i in lt){
lt[i] <- ifelse(lt[i] > 0, log(lt[i]), 0)
}

## got this error message
Error in ifelse(lt[i] > 0, log(lt[i]), 0) : 
  (list) object cannot be coerced to type 'double'

Aucun commentaire:

Enregistrer un commentaire