将函数应用于列表列表中的一个元素

问题描述 投票:0回答:1

我有

mylist
一系列列表,如下:

list1 <- list(label = c(2,8,9,5,9,10,0,1), code = c(585,652,756,255,365,123), name = c("cow", "sheep", "fox", "dog", "cat"))
list2 <- list(label = c(12,2,0,3,2,11,4,5), code = c(423,912,82,171,812,712), name = c("cow", "sheep", "fox", "dog", "cat"))
list3 <- list(label = c(10,7,9,1,3,14,8,6), code = c(372,465,962,23,702,12), name = c("cow", "sheep", "fox", "dog", "cat"))
mylist <- list(list1, list2, list3)

我的实际列表是 10000 个甚至更多这样的列表。

我想随机化所有列表中“名称”中值的顺序,而不触及“标签”和“代码”。期望的输出如下

list1 <- list(label = c(2,8,9,5,9,10,0,1), code = c(585,652,756,255,365,123), name = c("sheep", "fox", "cat", "cow", "dog"))
list2 <- list(label = c(12,2,0,3,2,11,4,5), code = c(423,912,82,171,812,712), name = c("sheep", "cow", "cat", "fox", "dog"))
list3 <- list(label = c(10,7,9,1,3,14,8,6), code = c(372,465,962,23,702,12), name = c("cat", "dog", "sheep", "fox", "cow"))
mylist <- list(list1, list2, list3)

我所做的就是使用以下内容随机化所有三个元素(“标签”,“代码”,“名称”)

lapply(mylist, function(x) sapply(x, sample))
r list loops lapply
1个回答
0
投票

你可以做

lapply(mylist, \(l) {l[["name"]] = sample(l[["name"]], length(l[["name"]]), FALSE); l})

注意

FALSE
指的是
replace
的参数
sample
。看看
help(sample)
。这可以重写得更简洁。然而,简化的解决方案取决于您的预期输出和更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.