我可能会误解您在这里要计算的内容,但是如果您想要每个列表的 arg1、arg2、arg3 的分数,或者所有列表中 arg、arg2、arg3 的分数,您可以执行以下操作来获得比例:
lol <- setNames(list(
setNames(as.list(1:3), c("arg1", "arg2", "arg3")),
setNames(as.list(4:6), c("arg1", "arg2", "arg3")),
setNames(as.list(7:9), c("arg1", "arg2", "arg3"))
), paste0("list", 1:3))
loldf <- do.call(rbind, lapply(lol, unlist))
loldf
#> arg1 arg2 arg3
#> list1 1 2 3
#> list2 4 5 6
#> list3 7 8 9
# proportion of each argument per list
round(100*prop.table(loldf, 1), 2)
#> arg1 arg2 arg3
#> list1 16.67 33.33 50.0
#> list2 26.67 33.33 40.0
#> list3 29.17 33.33 37.5
# proportion of single arguments over lists
round(100*prop.table(loldf, 2), 2)
#> arg1 arg2 arg3
#> list1 8.33 13.33 16.67
#> list2 33.33 33.33 33.33
#> list3 58.33 53.33 50.00
如果您喜欢data.table,您可以像这样获得相同的结果(在此处拆分为列表):
library(data.table)
lol <- setNames(list(
setNames(as.list(1:3), c("arg1", "arg2", "arg3")),
setNames(as.list(4:6), c("arg1", "arg2", "arg3")),
setNames(as.list(7:9), c("arg1", "arg2", "arg3"))
), paste0("list", 1:3))
lmao <- melt(rbindlist(lol, idcol = "name"), id.vars="name")
# proportion of each argument per list
split(lmao[, .(arg=unique(variable), n=value, Percent=round(100*value/sum(value), 2)),
by=.(name)], by="name", keep.by = FALSE)
#> $list1
#> arg n Percent
#> 1: arg1 1 16.67
#> 2: arg2 2 33.33
#> 3: arg3 3 50.00
#>
#> $list2
#> arg n Percent
#> 1: arg1 4 26.67
#> 2: arg2 5 33.33
#> 3: arg3 6 40.00
#>
#> $list3
#> arg n Percent
#> 1: arg1 7 29.17
#> 2: arg2 8 33.33
#> 3: arg3 9 37.50
# proportion of single arguments over lists
split(lmao[, .(list=unique(name), n=value, Percent=round(100*value/sum(value), 2)),
by=.(variable)], by="variable", keep.by = FALSE)
#> $arg1
#> list n Percent
#> 1: list1 1 8.33
#> 2: list2 4 33.33
#> 3: list3 7 58.33
#>
#> $arg2
#> list n Percent
#> 1: list1 2 13.33
#> 2: list2 5 33.33
#> 3: list3 8 53.33
#>
#> $arg3
#> list n Percent
#> 1: list1 3 16.67
#> 2: list2 6 33.33
#> 3: list3 9 50.00
由reprex package (v0.3.0) 于 2020-05-11 创建
编辑: tidyverse 版本
如果您愿意,下面是使用tidyverse 函数而不是data.table 的版本。
library(tidyverse)
lol <- setNames(list(
setNames(as.list (1:3), c("arg1", "arg2", "arg3")),
setNames(as.list (4:6), c("arg1", "arg2", "arg3")),
setNames(as.list (7:9), c("arg1", "arg2", "arg3"))
), paste0("list", 1:3))
lol %>% bind_rows(,.id="list") %>%
pivot_longer(-list) %>%
group_by(list) %>%
mutate(Percent=round(100*value/sum(value), 2)) %>%
split(., .$list)
#> $list1
#> # A tibble: 3 x 4
#> # Groups: list [1]
#> list name value Percent
#> <chr> <chr> <int> <dbl>
#> 1 list1 arg1 1 16.7
#> 2 list1 arg2 2 33.3
#> 3 list1 arg3 3 50
#>
#> $list2
#> # A tibble: 3 x 4
#> # Groups: list [1]
#> list name value Percent
#> <chr> <chr> <int> <dbl>
#> 1 list2 arg1 4 26.7
#> 2 list2 arg2 5 33.3
#> 3 list2 arg3 6 40
#>
#> $list3
#> # A tibble: 3 x 4
#> # Groups: list [1]
#> list name value Percent
#> <chr> <chr> <int> <dbl>
#> 1 list3 arg1 7 29.2
#> 2 list3 arg2 8 33.3
#> 3 list3 arg3 9 37.5
由reprex package (v0.3.0) 于 2020-05-12 创建