将新列添加到列表中的数据框

时间:2020-04-27 10:41:14

标签: r list lapply

我在名为my_list的列表中收集了一组名为df_1968,df_1969,df_1970,...,df_2016的数据帧。 我想在每个数据框中添加一个新列,它们只是当前年份(1968年在df_1968中,依此类推)。我已经设法通过遍历数据帧来做到这一点,但是我正在寻找一个更简洁的解决方案。我尝试了以下方法:

# Function to extract year from name of data frames
substrRight <- function(y,  n) {
substr(y, nchar(y) - n  + 1, nchar(y))
}

# Add variable "year" equal to 1968 in df_1968 and so on
my_list <- lapply(my_list, function(x) cbind(x, year <- as.numeric(substrRight(names(x), 4 ))))

但是这会引发错误:

Error in data.frame(..., check.names = FALSE) :
  arguments imply differing numbers of rows: 18878, 7

我可以看到,将值分配给变量的方式可能没有道理,但是我无法解决问题。帮助表示赞赏。

请注意,substrRight函数似乎运行正常,并且

as.numeric(substrRight(names(x), 4 ))

产生1968-2016年的向量

2 个答案:

答案 0 :(得分:0)

以下函数将遍历一个已命名的数据帧列表,并创建一个[[1 1 1 1 1] [0 1 1 1 1] [0 0 1 1 1] [0 0 0 1 1] [0 0 0 0 1]] 列,其中包含列表名称的最后4个字符。
我对功能year做了一些简化。由于这是所需的最后一个字符,因此它使用substrRight,而无需最后一个字符位置。

substring

数据创建代码。

substrRight <- function(y,  n) {
  substring(y, nchar(y) - n  + 1)
}

my_list <- lapply(names(my_list), function(x){
  my_list[[x]][["year"]] <- as.numeric(substrRight(x, 4))
  my_list[[x]]
})

答案 1 :(得分:0)

这在Base-R中有效

years <- sub(".*([0-9]{4}$)","\\1",names(my_list))
new_list <- lapply(1:length(years), function(x) cbind(my_list[[x]],year=years[x]))
names(new_list) <- names(my_list)

使用此示例数据

df_1968 = data.frame(a=c(1,2,3),b=c(4,5,6))
df_1969 = data.frame(a=c(1,2,3),b=c(4,5,6))
df_1970 = data.frame(a=c(1,2,3),b=c(4,5,6))

my_list <- list(df_1968,df_1969,df_1970)
names(my_list) <- c("df_1968","df_1969","df_1970")

我得到这个输出

> new_list
$df_1968
  a b year
1 1 4 1968
2 2 5 1968
3 3 6 1968

$df_1969
  a b year
1 1 4 1969
2 2 5 1969
3 3 6 1969

$df_1970
  a b year
1 1 4 1970
2 2 5 1970
3 3 6 1970