我想基于其rownames为列表中的每个数据框创建一个年列。这个问题has been asked before关于SO,但遗憾的是答案并没有帮助。那么, 有办法吗?
mylist <- list(structure(list(a = 1:10), .Names = "a", row.names = 1991:2000, class = "data.frame"),
structure(list(a = 1:10), .Names = "a", row.names = 1992:2001, class = "data.frame"))
预期结果:
[[1]]
a year
1991 1 1991
1992 2 1992
1993 3 1993
1994 4 1994
1995 5 1995
1996 6 1996
1997 7 1997
1998 8 1998
1999 9 1999
2000 10 2000
[[2]]
a year
1992 1 1992
1993 2 1993
1994 3 1994
1995 4 1995
1996 5 1996
1997 6 1997
1998 7 1998
1999 8 1999
2000 9 2000
2001 10 2001
答案 0 :(得分:4)
这是另一种选择:
lapply(mylist, function(df) transform(df, year = rownames(df)))
为了好玩,您还可以使用dplyr的add_rownames
功能:
lapply(mylist, dplyr::add_rownames, 'year')
答案 1 :(得分:2)
我们可以使用Map
Map(cbind, mylist, year= lapply(mylist, rownames))