[英]How to calculate length of vector within a list column (nested)
我有以下代碼
library(tidyverse)
dat <- iris %>%
group_by(Species) %>%
summarise(summary = list(fivenum(Petal.Width)))
dat
#> # A tibble: 3 x 2
#> Species summary
#> <fct> <list>
#> 1 setosa <dbl [5]>
#> 2 versicolor <dbl [5]>
#> 3 virginica <dbl [5]>
基本上我使用了Iris數據,按Species分組然后計算了fivenum()
。
我想要做的只是簡單地計算匯總值的長度:這是我嘗試過的但它沒有產生我期望的東西:
dat %>%
mutate(nof_value = length(summary))
# A tibble: 3 x 3
# Species summary nof_values
# <fct> <list> <int>
#1 setosa <dbl [5]> 3
#2 versicolor <dbl [5]> 3
#3 virginica <dbl [5]> 3
nof_values
應該都等於5.什么是正確的方法呢?
我們可以使用lengths
來計算嵌套列表的長度
library(tidyverse)
dat %>%
mutate(nof_values = lengths(summary))
# Species summary nof_values
# <fct> <list> <int>
#1 setosa <dbl [5]> 5
#2 versicolor <dbl [5]> 5
#3 virginica <dbl [5]> 5
其基數為R的等價物
dat$nof_values <- lengths(dat$summary)
旁注: length
與lengths
不同
length(dat$summary)
#[1] 3
lengths(dat$summary)
#[1] 5 5 5
您可以使用purrr包中的map_int命令(這是tidyverse的一部分)
dat <- iris %>%
group_by(Species) %>%
summarise(summary = list(fivenum(Petal.Width))) %>%
mutate(nof_value = map_int(summary, length))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.