0

I would like to have a loop over a list of data frames that converts specific columns from data frames as numeric(in my case its's second and third column of each data frame within the list) I already have some code here and don't know why it isn't working...

Could some1 help me ?

lapply(myfiles2[[]][[,c(2,3)]], as.numeric)
Razvan Cretu
  • 33
  • 3
  • 9
  • [Reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) example please... – Conor Neilson Nov 24 '18 at 19:41

1 Answers1

0

This is not so hard. Yoy have to loop (lapply) through the list changing each member data.frame's columns of interest with another call to lapply.

First, some example dataset, since you have posted none.

set.seed(1234)
myfiles2 <- lapply(1:4, function(i){
  data.frame(X = letters[1:5], Y = factor(sample(5)), Z = as.character(11:15))
})

str(myfiles2)    # output omited

Now, the problem.

cols <- 2:3
myfiles3 <- lapply(myfiles2, function(DF){
  DF[cols] <- lapply(DF[cols], as.numeric)
  DF
})

To see that it worked any of the following two will do.

lapply(myfiles3, function(DF) sapply(DF, class))

str(myfiles3)
#List of 4
# $ :'data.frame':  5 obs. of  3 variables:
#  ..$ X: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
#  ..$ Y: num [1:5] 1 3 2 4 5
#  ..$ Z: num [1:5] 1 2 3 4 5
# $ :'data.frame':  5 obs. of  3 variables:
#  ..$ X: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
#  ..$ Y: num [1:5] 4 1 5 2 3
#  ..$ Z: num [1:5] 1 2 3 4 5
# $ :'data.frame':  5 obs. of  3 variables:
#  ..$ X: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
#  ..$ Y: num [1:5] 4 3 1 2 5
#  ..$ Z: num [1:5] 1 2 3 4 5
# $ :'data.frame':  5 obs. of  3 variables:
#  ..$ X: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
#  ..$ Y: num [1:5] 5 2 1 3 4
#  ..$ Z: num [1:5] 1 2 3 4 5
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • Thank you so much. You're right, it was so simple, had thought about looping within each element of list and but I only made up something with (`for`) loops – Razvan Cretu Nov 25 '18 at 00:35