如何根据每个组件的名称在列表的所有组件中创建一个新列?
这是一个示例列表:
list1 <- list(a = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1),
d = c(2, 2, 2, 2)), class = "data.frame", row.names = c(NA,
-4L)), b = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1
), d = c(2, 2, 2, 2)), class = "data.frame", row.names = c(NA,
-4L)), d = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1
), d = c(2, 2, 2, 2)), class = "data.frame", row.names = c(NA,
-4L)))
我想在列表的每个组件(即A,B,d)中添加一个列,以便第四列指示组件的名称。这是我要寻找的例子。
list2 <- list(a = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1),
d = c(2, 2, 2, 2), name = structure(c(1L, 1L, 1L, 1L), class = "factor", .Label = "a")), class = "data.frame", row.names = c(NA,
-4L)), b = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1
), d = c(2, 2, 2, 2), name = structure(c(1L, 1L, 1L, 1L), class = "factor", .Label = "b")), class = "data.frame", row.names = c(NA,
-4L)), d = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1
), d = c(2, 2, 2, 2), name = structure(c(1L, 1L, 1L, 1L), class = "factor", .Label = "c")), class = "data.frame", row.names = c(NA,
-4L)))
我尝试过
list2 <- lapply(list1, function(x) cbind(list1, name = names(x[1])))
但无济于事。我了解为什么以上是不起作用的,但无法找到不同的解决方案。感谢您的帮助!
Here is an example list:
list1 <- list(a = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1),
d = c(2, 2, 2, 2)), class = "data.frame", row.names = c(NA,
-4L)), b = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1
), d = c(2, 2, 2, 2)), class = "data.frame", row.names = c(NA,
-4L)), d = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1
), d = c(2, 2, 2, 2)), class = "data.frame", row.names = c(NA,
-4L)))
I would like to add a column inside each component of the list (i.e. a, b, d) such that the fourth column indicates the name of component. Here's an example of what I'm looking for.
list2 <- list(a = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1),
d = c(2, 2, 2, 2), name = structure(c(1L, 1L, 1L, 1L), class = "factor", .Label = "a")), class = "data.frame", row.names = c(NA,
-4L)), b = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1
), d = c(2, 2, 2, 2), name = structure(c(1L, 1L, 1L, 1L), class = "factor", .Label = "b")), class = "data.frame", row.names = c(NA,
-4L)), d = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1
), d = c(2, 2, 2, 2), name = structure(c(1L, 1L, 1L, 1L), class = "factor", .Label = "c")), class = "data.frame", row.names = c(NA,
-4L)))
I have tried variants of
list2 <- lapply(list1, function(x) cbind(list1, name = names(x[1])))
but to no avail. I understand why the above wouldn't work, but couldn't figure out a different solution. Thanks for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们可以使用
imap
或
基本r
与map
的
以
lapply
序列或名称We can use
imap
Or in
base R
withMap
-output
With
lapply
, it can be done by looping over the sequence or names