R:跨多个对象重新编码变量

R: Recoding Variables Across Multiple Objects

提前感谢您的建议。我正在尝试在循环中的多个对象上创建一个新变量。这些新变量是由函数生成的。

比如我有三组国家级数据:

# Generate Example Data
`enter code here`pop <- data.frame(country=c("US","US","CA","CA","FR","FR"),year=c(1,2,1,2,1,2),value=c(290,300,29,30,50,55))
gas <- data.frame(country=c("US","US","CA","CA","FR","FR"),year=c(1,2,1,2,1,2),value=c(3.10,1.80,4.50,2.50,4.50,2.50))
cars <- data.frame(country=c("US","US","CA","CA","FR","FR"),year=c(1,2,1,2,1,2),value=c(2.1,2.2,1.8,1.9,1.3,1.3))

我想创建一个名为“countrycode”的新变量,使用 countrycode 包中的 countrycode() 命令。

我会像这样对单个对象执行操作:

library(countrycode)
pop$ccode <- countrycode(pop$country,"iso2c","cown")
pop$id <- (pop$ccode*10000)+pop$year

但是我有大量的对象。我希望像这样循环执行此操作

# Create list of variables
vars <- c("pop","gas","cars")
for (i in vars){
  i$ccode <- countrycode(country,"iso2c","cown")
  i$id <- (i$ccode*10000)+i$year
}

但这行不通。我一直在尝试在循环中使用 assign()apply() 来做到这一点,但我太笨了,无法理解如何在我的案例中完成这项工作。

如果有人可以向我提供如何使用我自己的数据类型执行此操作的示例,我将不胜感激。

这对你有用吗?

pop <- data.frame(country=c("US","US","CA","CA","FR","FR"),year=c(1,2,1,2,1,2),value=c(290,300,29,30,50,55))
gas <- data.frame(country=c("US","US","CA","CA","FR","FR"),year=c(1,2,1,2,1,2),value=c(3.10,1.80,4.50,2.50,4.50,2.50))
cars <- data.frame(country=c("US","US","CA","CA","FR","FR"),year=c(1,2,1,2,1,2),value=c(2.1,2.2,1.8,1.9,1.3,1.3))


attachCodes <- function(dframe)
{
  df <- dframe
  df$ccode <- countrycode(df$country,"iso2c","cown")
  df$id <- (df$ccode*10000)+df$year
  return(df)
}

tablesList <- list(pop,gas,cars)
tablesList <- lapply(tablesList,attachCodes)

特别感谢@Pawel 提供解决问题所需的缺失信息。解决方案是:

rm(list=ls())
pop <- data.frame(country=c("US","US","CA","CA","FR","FR"),year=c(1,2,1,2,1,2),value=c(290,300,29,30,50,55))
gas <- data.frame(country=c("US","US","CA","CA","FR","FR"),year=c(1,2,1,2,1,2),value=c(3.10,1.80,4.50,2.50,4.50,2.50))
cars <- data.frame(country=c("US","US","CA","CA","FR","FR"),year=c(1,2,1,2,1,2),value=c(2.1,2.2,1.8,1.9,1.3,1.3))


attachCodes <- function(dframe)
{
  df <- dframe
  df$ccode <- countrycode(df$country,"iso2c","cown")
  df$id <- (df$ccode*10000)+df$year
  return(df)
}

names <- list("pop","gas","cars")
for(i in names){
  assign(i,attachCodes(get(i)))
}