gpt4 book ai didi

r - 从列表中提取累积的唯一元素

转载 作者:行者123 更新时间:2023-12-04 02:46:20 25 4
gpt4 key购买 nike

我有一个列表:

z <- vector("list", 3)
z[[1]]=c(1,2,3,4)
z[[2]]=c(1,6,2,9)
z[[3]]=c(1,2,3,4,5)

我想创建一个包含列表 (3) 中所有项目的列矩阵

A=matrix(0,3,1)

我希望矩阵的每一行都包含 Z 列表中以前从未见过的唯一元素的累积数量。例如,

矩阵应填充为:

     [1]
A=[1] 4
[2] 6
[3] 7

(4 因为每个元素都是新的,然后是 6 因为之前在 z[[1]] 中看到过其他元素,然后是 7 因为 5 是唯一的新元素。)

有谁知道这样做的好方法吗?我可以通过在 3 上循环并制作一个虚拟矩阵并在 if 条件下进行独特和测试来以一种非常愚蠢的方式对其进行编程,但这似乎有点过分。

感谢您的宝贵时间。

最佳答案

我认为您需要使用允许迭代循环的东西,所以我在这里使用 for 循环。我们获取所有唯一元素,对于 z 中的每个元素,我们求和唯一元素中的值,然后在下一次迭代中删除它们...

#  Get unique elements
elems <- unique( unlist( z ) )

# Pre allocate result vector
tot <- numeric(length(z))

for( i in 1:length(z) ){
# How many unique elements are in this list element
tot[i] <- sum( z[[i]] %in% elems )
# Remove them from the list so they are not counted in the next iteration
elems <- elems[ ! elems %in% z[[i]] ]
}

# Get the cumulative sum
cumsum( tot )
[1] 4 6 7

关于r - 从列表中提取累积的唯一元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18757068/

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