1

I have 10 data frames which include climate data. Column no 1, is "date" column the class of which is character. The date format is "1/5/19". I want to separate this column into 3 other columns using a for loop for all my data frames. At first, I've created a vector named "onomata" which contains the data frame names:

onomata <- c("agia_paraskeui","ano_liosia","athens_gazi","marina",
         "kifisia","marousi","nea_smyrni","patisia","peristeri",
         "psychico")

Then I used the "separate" function from tidyr package, and I tested the function for one data frame:

agia_paraskeui <- separate(agia_paraskeui, col = date,
                         into = c("day","month","year"), sep = "/")

It worked as it should be, and then I tried to apply that to all data frames by using the next for loop:

    for(i in onomata){
  i <- separate(i, col = date,
                        into = c("day","month","year"), sep = "/")
}

It didn't work. Instead I received the following error message:

"Error in UseMethod("separate_") : no applicable method for 'separate_' applied to an object of class "character"

What do you think is the problem ?

Kon Ath
  • 183
  • 1
  • 2
  • 13

1 Answers1

1

If it needs to be applied on a loop, use map. The objects names are string. We need to get the value of the objects. If there are more than one, use mget and it returns the value of the objects in a list. Loop over the list, and apply separate

library(dplyr)
library(tidyr)
library(purrr)
map(mget(onomata), ~ separate(.x, col = date,
    into = c("day","month","year"), sep = "/"))

Also, with a loop

out <- vector('list', length(onomata))
for(i in seq_along(onomata)) {
   out[[i]] <- separate(get(onomata[i]), col = date,
    into = c("day","month","year"), sep = "/")
  }
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thank you very much! It worked, and your explanation is very helpful in order to repeat a similar process in the future !!! – Kon Ath May 08 '21 at 18:26