向dataframe添加新列,该列是for循环R中dataframe的名称?

向dataframe添加新列,该列是for循环R中dataframe的名称?,r,for-loop,R,For Loop,我有一个数据帧列表,我想在每个数据帧中创建一个新列,它是数据帧的名称。然而,我做这件事有困难 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("ye

我有一个数据帧列表,我想在每个数据帧中创建一个新列,它是数据帧的名称。然而,我做这件事有困难

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
 }

等等。

您可以使用
mget
将数据放入一个列表,然后使用
cbind
Map
添加新列

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

...
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

...