R error when calling a function with lapply -


i have dataset column composed numbers

dati$score[10:15] [1]   7576   6362 764663 676164 764676   6364 

i have function calculates sums of number in cell found here on stackoverflow , works when apply singularly

digitsum <- function(x) sum(floor(x / 10^(0:(nchar(x) - 1))) %% 10) 

i can't apply column dati$score, error, i've tried using lapply , cycle

for (i in 1:lunghscore){ f <-  dati[i,"score"]  post <- sum(floor(f / 18^(0:(nchar(f) - 1))) %% 18) dati[i,"score"] <- post <- + 1 } 

lapply

dati[,"score"] <- lapply(x = dati[,"score"],fun = digitsum) 

i error

   2: in `[<-.data.frame`(`*tmp*`, , "score", value = list(20, 17, 26,  : provided 66121 variables replace 1 variables 

how can apply function digitsum every cell in column?

the problem output of list list, , fill vector elements of list. code works if unlist lapply function shown in pet example below:

> digitsum <- function(x) sum(floor(x / 10^(0:(nchar(x) - 1))) %% 10) > dati <- data.frame(matrix(250:255, ncol = 2)) > dati    x1  x2 1 250 253 2 251 254 3 252 255  > lapply(dati[, "x2"], digitsum) [[1]] [1] 10  [[2]] [1] 11  [[3]] [1] 12  > dati[, "x2"]<-lapply(dati[, "x2"], digitsum) warning message: in `[<-.data.frame`(`*tmp*`, , "x2", value = list(10, 11, 12)) :   provided 3 variables replace 1 variables 

and solution:

> dati[, "x2"]<-unlist(lapply(dati[, "x2"], digitsum)) 

best, thomas


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -