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

时间:2016-01-29 18:02:21

标签: r data-manipulation

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

例如,我有三组国家级数据:

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

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

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

# 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
}

但我有很多物品。我希望在循环中这样做,就像这样

{{1}}

但这不起作用。我一直在尝试使用循环中的 assign() apply()来执行此操作,但我太过密集以至于无法理解如何在我的情况。

如果有人能够提供一个如何使用我自己的数据来做这个的例子,我将非常感激。

2 个答案:

答案 0 :(得分:0)

这对你有用吗?

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)

答案 1 :(得分:0)

特别感谢@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)))
}