mjoy
mjoy

Reputation: 680

Add new column to dataframe that is the name of dataframe in for loop R?

I have a list of data frames and I want to create a new column in each data frame that is the name of the dataframe. However, I am having trouble doing this.

new_list <- c("NY", "CA", "MI", "VA", "WY")

NY <- data.frame(phrase = c("one_two", "two_one", "three"))
CA <- data.frame(phrase = c("blue", "green", "three"))
MI <- data.frame(phrase = c("yellow", "green", "two"))
VA <- data.frame(phrase = c("two_one", "one_two", "orange"))
WY <- data.frame(phrase = c("green", "orange", "three"))

for (x in new_list){
   state <- x
   x <- get(x)
   x$geo <- town
 }

I want the result to look like:

   NY:    phrase        state
         one_two         NY
         two_one         NY
          three          NY

etc.

Upvotes: 0

Views: 29

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99321

You can use mget to put the data into a list, then Map with cbind to add the new column.

Map(cbind, mget(new_list), state = new_list)
# $NY
#    phrase state
# 1 one_two    NY
# 2 two_one    NY
# 3   three    NY
#
# $CA
#   phrase state
# 1   blue    CA
# 2  green    CA
# 3  three    CA

...

Upvotes: 1

Related Questions