Home > Software engineering >  loop through multiple dataframes and save column names using glue R
loop through multiple dataframes and save column names using glue R

Time:05-31

I am trying to save column names from multiple dataframes in R. I am currently using string syntax with Glue but currently i just keep getting 'NULLs'

I have structured an example here. I have these two dataframes below:

over50_one <- c("n", "n", "n", "y", "n")
Gender_one <- c("F", "F", "M", "M", "F")
Name_one <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age_one <- c(23, 41, 32, 58, 26)

df_one <- data.frame(Name_one, Age_one,Gender_one,over50_one)

over50_two <- c("n", "n", "n", "y", "n")
Gender_two <- c("F", "F", "M", "M", "F")
Name_two <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age_two <- c(23, 41, 32, 58, 26)

df_two <- data.frame(Name_two, Age_two,Gender_two,over50_two)

and i create this loop to save the column names to 'names':

list_loop <- c('one','two')

for(number in list_loop) {                 # Head of for-loop
  print(number)
  names <-  names(glue('df_{number}'))
  print(names)
}

but the output i get for names is NULL, when i should get over50_one, gender_one, name_one etc etc etc. Any help would be wonderful.

CodePudding user response:

A couple of things going on here. Firstly you are assigning the name object the name names, which is also the name of the function you are calling. You should call it my_names or similar.

Secondly, when you do names(glue('df_{number}')), you are doing names('df_one') on the first iteration, i.e. the names of the character vector containing one element, not the data frame called df_one. That vector does not have any names, hence it returns NULL.

Instead of using glue, I would do something like:

list_loop  <- ls(pattern = "^df_")

for(my_df in list_loop) {
  print(my_df)                 # Head of for-loop
  my_names <-  names(get(my_df))
  print(my_names)
}

# [1] "df_one"
# [1] "Name_one"   "Age_one"    "Gender_one" "over50_one"
# [1] "df_two"
# [1] "Name_two"   "Age_two"    "Gender_two" "over50_two"
  • Related