我有
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))
你可以做
lapply(mylist, \(l) {l[["name"]] = sample(l[["name"]], length(l[["name"]]), FALSE); l})
注意
FALSE
指的是replace
的参数sample
。看看help(sample)
。这可以重写得更简洁。然而,简化的解决方案取决于您的预期输出和更多信息。