计算递归列表中的元素 [英] Count elements in recursive list

查看:100
本文介绍了计算递归列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算递归列表中的元素? 这是数据,但可能是更大的列表.

How can I count elements in recursive list? Here is data, but it could be bigger list.

data <- list(list(list("a"), list("b"), list("c","d","e")), list("f"))

> str(data)
List of 2
 $ :List of 3
  ..$ :List of 1
  .. ..$ : chr "a"
  ..$ :List of 1
  .. ..$ : chr "b"
  ..$ :List of 3
  .. ..$ : chr "c"
  .. ..$ : chr "d"
  .. ..$ : chr "e"
 $ :List of 1
  ..$ : chr "f"

在输出中,我想使用百分比使用总计为100%的向量:

On output I want to have vector with % usage which sums to 100%:

o <- c(1/2/3/1, 1/2/3/1, 1/2/3/3, 1/2/3/3, 1/2/3/3, 1/2/1)
[1] 0.16666667 0.16666667 0.05555556 0.05555556 0.05555556 0.50000000
sum(o)
[1] 1

所以我需要v1(只是分配代表= 100%):

So I need v1 (is just rep of allocation = 100%):

v1 <- rep(1, length( unlist(data) ))
v1
[1] 1 1 1 1 1 1

v2:

> v2 <- rep(length(data), length( unlist(data) ))
> v2
[1] 2 2 2 2 2 2

v3,

> v3 = c(3, 3, 3, 3, 3, 1)

v4:

v4 = c(1,1,3,3,3,1)

v4 = c(1, 1, 3, 3, 3, 1)

结果:

> v1/v2/v3/v4
[1] 0.16666667 0.16666667 0.05555556 0.05555556 0.05555556 0.50000000
sum(v1/v2/v3/v4)
[1] 1

所以问题是我如何制作v3和v4等?

So question is how I can make v3 and v4 etc. ?

也许有办法获取每个孩子的str(data)计数长度的向量,如:

Maybe is there way to get vector of str(data) count length of each child like:

out <- c("2/3/1", "2/3/1", "2/3/3", "2/3/3", "2/3/3", "2/1")

然后用这个向量我可以做数学:

Then with this vector I can do math:

> sapply(out, function(x) last(cumprod(1 / c(1, as.numeric(unlist(strsplit(x, "/")))))))
     2/3/1      2/3/1      2/3/3      2/3/3      2/3/3        2/1 
0.16666667 0.16666667 0.05555556 0.05555556 0.05555556 0.50000000 

推荐答案

这使其适用于递归解决方案,可能类似于:

This lends itself to a recursive solution, possibly something like:

data <- list(list(list("a"), list("b"), list("c","d","e")), list("f"))


f <- function(x, prop=1)
{
  if(is.list(x)) lapply(x, f, prop=prop/length(x))
  else prop/length(x)
}

unlist(f(data))

#[1] 0.16666667 0.16666667 0.05555556 0.05555556 0.05555556 0.50000000

这篇关于计算递归列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆