David Potrel
David Potrel

Reputation: 111

Loop for on dataset name in R

This topic has been covered numerous times I see but I can't really get the answer I'm looking for. Thus, here I go.

I am trying to do a loop to create variables in 5 data sets that have similar names as such:

Ech_repondants_nom_1 Ech_repondants_nom_2 Ech_repondants_nom_3 Ech_repondants_nom_4 Ech_repondants_nom_5

Below if the code that I have tried:

list <- c(1:5)

for (i in list) {

Ech_repondants_nom_[[i]]$sec = as.numeric(Ech_repondants_nom_[[i]]$interviewtime)
Ech_repondants_nom_[[i]]$min = round(Ech_repondants_nom_[[i]]$sec/60,1)
Ech_repondants_nom_[[i]]$heure = round(Ech_repondants_nom_[[i]]$min/60,1)

}

Any clues why this does not work?

cheers!

Upvotes: 1

Views: 1315

Answers (2)

tjaqu787
tjaqu787

Reputation: 327

Ech_repondants_nom_[[i]]

Isn't actually selcting that dataframe because you can't call objects like that. Try creating a function that takes a dataframe as an argument then iterating through the dataframes

changing_time_stamp<-function(df){
    df$sec = as.numeric(df$interviewtime)
    df$min = round(df$sec/60,1)
    df$heure = round(df$min/60,1)

for (i in list) {
    changing_time_stamp(i)
}

EDIT: I fixed some of the variable names in the function

Upvotes: 1

akrun
akrun

Reputation: 887118

These are object names and not list elements to subset as Ech_repondants_nom_[[i]]. We may need to get the object by paste i.e.

get(paste0("Ech_repondants_nom_", i)$sec

but, then if we need to update the original object, have to call assign. Instead of all this, it can be done more easily if we load the datasets into a list and loop over the list with lapply

lst1 <- lapply(mget(paste0("Ech_repondants_nom_", 1:5)), function(dat)
     within(dat, {sec <- as.numeric(interviewtime);
                  min <- round(sec/60, 1);
                  heure <- round(min/60, 1)}))

It may be better to keep it as a list, but if we need to update the original object, use list2env

list2env(lst1, .GlobalEnv)

Upvotes: 1

Related Questions