0

I have got a lot of data frames in my R environment and I want to do the as.numeric() function on all of the variables in the data.frames and overwrite them. I do not know how to address all of them.

The following is my attempt, but ls() seemingly just writes the name to x:

for  (i in 1:length(ls())){
       x <- ls()[i]
       for (i in 1:length(x)){
         x[i] <- as.numeric(x[i])
       }
}
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
bash-asker
  • 41
  • 5
  • Store them in a list instead and then just use lapply and as.numeric - it’s **much** better to do this than have them all cluttering up your environment – user438383 Aug 03 '22 at 10:02
  • I have got 3600 CSV files, of which the file names contain important information on participant and measurement. I alternatively tried saving it in a list, but the filenames are not there anymore. Also I tried the as.numeric command using lapply but this did not work, saying "'list' object cannot be coerced to type 'double'". `temp = list.files(pattern="*.csv") myfiles = lapply(temp, read.csv2) myfiles_num <- lapply(myfiles, as.numeric)` – bash-asker Aug 03 '22 at 10:10
  • Read [How do I make a list of data frames?](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207), "I didn't put my data in a list :( I will next time, but what can I do now?". Then see `?type.convert` – Henrik Aug 03 '22 at 10:12
  • Darran Tsai's method worked. Thank you very much. I am still interested in Henriks way of storing in a list, preserving the file.names in the list AND converting to numerical. Is @Henrik comment the full function? In later steps, I want to combine data frames who have specific patterns in the name. Is this possible while in the list? – bash-asker Aug 03 '22 at 10:36

1 Answers1

0

So, there were two helpful answers to my question. One, that was later deleted and another one by @Henrik.

The deleted one followed my approach to convert all data frames in global environment (that has an "V" in it - in my example) as numerics. This is the code:

res <- lapply(mget(ls(pattern = 'V')), \(x) {
  x[] <- lapply(x, as.numeric)
  return(x)
})

list2env(res, .GlobalEnv)

# Check
str(VA01.000306__ft2)

The second approach uses lists instead of multiple objects. When I have stored my multiple csv files into lists. This is the csv to list import:

F_EB_names <- list.files(pattern="*.csv")### Daten in Liste speichern?
F_EB  <- lapply(F_EB_names, read.csv2)
names(F_EB) <- gsub(".wav.csv","_ft2",F_EB_names)

And this is the conversion to numerals:

F_EB <- type.convert(F_EB) # Conversion
str(F_EB) # Check

Thank you both for the help.

bash-asker
  • 41
  • 5