0

I have a list of dataframes and I want to create a new column in each of those dataframes that is the name of the dataframe, which I also have in another list. I'm not sure why but it ends up creating a new dataframe that only consists of the last dataframe in my list.

schema <- "x"
table_prefix <- "results_"
geos <- district %>% filter(geo != "geo")

for (geo in geos){
  tables <- paste0(schema, ".", table_prefix, geo)
  queries <-   paste("SELECT * FROM", tables)
}


i = 1
df_list <- list()
for (x in queries){
  name <- substr(x, 40, nchar(x))
  df_list[i] <- name
  assign(name, dbGetQuery(con, x))
  i = i + 1
}

dfs <- lapply(df_list, get)

i = 1
for (x in dfs){
  x$geo <- df_list[i]
  i = i + 1
} 


full_df <- do.call(rbind, dfs)

This ends up giving me a new dataframe called 'x' that has the contents of the last dataframe in my list with the new column I want. How can I get it so all the dataframes get a new column with their name?

1 Answer 1

1

Try this:

for (i in 1:length(dfs)){
  dfs[[i]]$geo <- df_list[i]
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.