简体   繁体   中英

loop through multiple dataframes and save column names using glue R

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.

A couple of things going on here. Firstly you are calling your object names , which is also the name of a function you are calling. This is going to cause you problems after the first iteration of the loop. 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, ie 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM