gpt4 book ai didi

r - 在for循环中获取列表名称

转载 作者:行者123 更新时间:2023-12-04 10:09:50 26 4
gpt4 key购买 nike

在PHP中,您可以使用以下命令在for循环中访问数组的名称和值:

foreach ( $array as $key => $value ) {

遍历命名列表时,R中有可比的东西吗?

最佳答案

使用一些虚拟数据和一个愚蠢的人为例子

ll <- list(A = 1:10, B = LETTERS[1:10], C = letters[1:10])

您可以在 lapply()元素的索引上 ll:
out <- lapply(seq_along(ll),
function(ind, list, names) {
paste(names[ind], "=", paste(list[[ind]], collapse = ", "))
}, list = ll, names = names(ll))

R> out
[[1]]
[1] "A = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10"

[[2]]
[1] "B = A, B, C, D, E, F, G, H, I, J"

[[3]]
[1] "C = a, b, c, d, e, f, g, h, i, j"

for()遍历列表:
ll2 <- vector("list", length(ll))
nams <- names(ll)
for(i in seq_along(ll)) {
ll2[[i]] <- paste(nams[i], "=", paste(ll[[i]], collapse = ", "))
}
ll2

R> ll2
[[1]]
[1] "A = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10"

[[2]]
[1] "B = A, B, C, D, E, F, G, H, I, J"

[[3]]
[1] "C = a, b, c, d, e, f, g, h, i, j"

关于r - 在for循环中获取列表名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11112750/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com