为for循环中的多个数据帧创建新变量

为for循环中的多个数据帧创建新变量,r,dataframe,for-loop,R,Dataframe,For Loop,我有8个数据帧,我想为每个数据帧创建一个变量。我使用for a循环,我使用的代码如下所示: year <- 2001 dflist <- list(bhps01, bhps02, bhps03, bhps04, bhps05, bhps06, bhps07, bhps08) for (df in dflist){ df[["year"]] <- as.character(year) assign() year <- year + 1 } yearfor循环中的语法错误

我有8个数据帧,我想为每个数据帧创建一个变量。我使用for a循环,我使用的代码如下所示:

year <- 2001
dflist <- list(bhps01, bhps02, bhps03, bhps04, bhps05, bhps06, bhps07, bhps08)

for (df in dflist){
df[["year"]] <- as.character(year)
assign()
year <- year + 1
}

yearfor循环中的语法错误。我不完全确定你想要完成什么,但让我们试试这个

year = 2001 

A = data.frame(a = c(1, 1), b = c(2, 2))
B = data.frame(a = c(1, 1), b = c(2, 2))
L = list(A, B)

for (i in seq_along(L)) {
  L[[i]][, dim(L[[i]])[2] + 1] = as.character(rep(year,dim(L[[i]])[1]))  
  year = year + 1
}
有输出

> L
[[1]]
  a b   V3
1 1 2 2001
2 1 2 2001

[[2]]
  a b   V3
1 1 2 2002
2 1 2 2002
这就是你想要的输出,对吗

要将列名更改为“年”,可以执行以下操作

L = lapply(L, function(x) {colnames(x)[3] = "year"; x})

您从列表中获取数据帧的副本,并将变量“year”添加到其中,但不将其分配到任何位置,这就是它被丢弃(即不存储在变量中)的原因。这里有一个解决方案:

year <- 2001
dflist <- list(bhps01, bhps02, bhps03, bhps04, bhps05, bhps06, bhps07, bhps08)

counter <- 0
for (df in dflist){
  counter <- counter + 1
  df[["year"]] <- as.character(year)
  dflist[[counter]] <- df
  year <- year + 1
}

一年来我一直在尝试这个代码。代码运行正常,但变量年份不会在这两个数据帧中创建。这是因为当您使用bhps01、02等创建数据帧时,更改现在位于您创建的列表(dflist)中。如果您想让每个单独的数据帧都具有year变量,您可以将它们重新分配。循环完成后:bhps01如何实现bhps01的自动化我用以下代码进行了尝试:
year=2001 L我有8个数据帧,即bhps01、bhps02、bhps03、bhps04、bhps05、bhps06、bhps07和bhps08。每个数据对应一年,因此bhps01对应2001年,bhps对应2002年,依此类推。所以,我想为这些数据中的每一个创建一个年份变量。因此,对于bhps01数据,年份变量为“2001”,对于bhps02数据,年份变量为“2002”,依此类推。我希望现在一切都清楚了?对不起,有个打字错误!尝试此
year=2001 L在代码这次运行时,但仍然没有为任一数据帧创建变量“year”?不,该变量可能是
V3
。不过,您可以使用命令
L=lappy(L,函数(x){colnames(x)[3]=“year”;x})重命名它。现在能用了吗?
year <- 2001
dflist <- list(bhps01 = bhps01, bhps02 = bhps02, bhps03 = bhps03, bhps04 = bhps04, bhps05 = bhps05, bhps06 = bhps06, bhps07 = bhps07, bhps08 = bhps08)

counter <- 0
for (df in dflist){
  counter <- counter + 1
  df[["year"]] <- as.character(year)
  dflist[[counter]] <- df
  assign(names(dflist)[counter], df)
  year <- year + 1
}