GGA
GGA

Reputation: 385

R error when calling a function with lapply

I have a dataset with a column composed by numbers

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

I have this function which calculates the sums of the number in a cell which i found here on stackoverflow and works when i apply it singularly

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

I can't apply this to the column dati$score, i get this error, i've tried using lapply and a for cycle

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

lapply

dati[,"score"] <- lapply(X = dati[,"score"],FUN = digitsum)

I get this error

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

How can i apply the function digitsum to every cell in that column?

Upvotes: 0

Views: 1793

Answers (1)

tomtom
tomtom

Reputation: 259

The problem is that the output of a list is always a list, and you fill a vector with elements of a list. Your code works if you unlist your lapply function as shown in the 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 to replace 1 variables

And the solution:

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

Best, Thomas

Upvotes: 1

Related Questions