对于R中的每一类数据,依次执行代码的方法是什么



假设有任何代码,无论它多么简单和复杂,它都必须与存在某种grouping variable的数据一起工作。因此,作为可重复的例子,我们可以看到iris数据集。iris$Species分为三类(刚毛、处女、云芝(。假设我想要每个species的度量变量之间的简单操作相关性。我可以做

dt=iris[species==virginic] `(data.table)`

然后执行CCD_ 5。但是,让我们想象这样一种情况,代码是复杂的、巨大的(甚至作为一个例子来阐述它都没有意义(,并且分组变量(groupvar(中有许多类别。

对于每个类别,它依次工作的方式是什么?即,首先,为groupware=1处理代码,处理后,它开始处理属于groupware=2的行,依此类推,对于群件中的所有类别,直到一切都通过。

关于相同虹膜的例子

[1]setosa
some calculation code.., 
[2] virginic 
some calculation code.., ,
[3] versicol
some calculation code.., 

因为如果有数千个类别,我无法手动为每个类别设置过滤器。可以做些什么使代码分别对分组变量的所有类别起作用?谢谢你的宝贵帮助。

如果我正确理解

# tidyverse
library(tidyverse)
iris %>% 
group_split(Species) %>% 
map(~cor(select(.x, where(is.numeric))))
#> [[1]]
#>              Sepal.Length Sepal.Width Petal.Length Petal.Width
#> Sepal.Length    1.0000000   0.7425467    0.2671758   0.2780984
#> Sepal.Width     0.7425467   1.0000000    0.1777000   0.2327520
#> Petal.Length    0.2671758   0.1777000    1.0000000   0.3316300
#> Petal.Width     0.2780984   0.2327520    0.3316300   1.0000000
#> 
#> [[2]]
#>              Sepal.Length Sepal.Width Petal.Length Petal.Width
#> Sepal.Length    1.0000000   0.5259107    0.7540490   0.5464611
#> Sepal.Width     0.5259107   1.0000000    0.5605221   0.6639987
#> Petal.Length    0.7540490   0.5605221    1.0000000   0.7866681
#> Petal.Width     0.5464611   0.6639987    0.7866681   1.0000000
#> 
#> [[3]]
#>              Sepal.Length Sepal.Width Petal.Length Petal.Width
#> Sepal.Length    1.0000000   0.4572278    0.8642247   0.2811077
#> Sepal.Width     0.4572278   1.0000000    0.4010446   0.5377280
#> Petal.Length    0.8642247   0.4010446    1.0000000   0.3221082
#> Petal.Width     0.2811077   0.5377280    0.3221082   1.0000000
# base
COLS <- sapply(iris, is.numeric)
l <- split(iris, iris$Species)
lapply(l, function(x) cor(x[COLS]))
#> $setosa
#>              Sepal.Length Sepal.Width Petal.Length Petal.Width
#> Sepal.Length    1.0000000   0.7425467    0.2671758   0.2780984
#> Sepal.Width     0.7425467   1.0000000    0.1777000   0.2327520
#> Petal.Length    0.2671758   0.1777000    1.0000000   0.3316300
#> Petal.Width     0.2780984   0.2327520    0.3316300   1.0000000
#> 
#> $versicolor
#>              Sepal.Length Sepal.Width Petal.Length Petal.Width
#> Sepal.Length    1.0000000   0.5259107    0.7540490   0.5464611
#> Sepal.Width     0.5259107   1.0000000    0.5605221   0.6639987
#> Petal.Length    0.7540490   0.5605221    1.0000000   0.7866681
#> Petal.Width     0.5464611   0.6639987    0.7866681   1.0000000
#> 
#> $virginica
#>              Sepal.Length Sepal.Width Petal.Length Petal.Width
#> Sepal.Length    1.0000000   0.4572278    0.8642247   0.2811077
#> Sepal.Width     0.4572278   1.0000000    0.4010446   0.5377280
#> Petal.Length    0.8642247   0.4010446    1.0000000   0.3221082
#> Petal.Width     0.2811077   0.5377280    0.3221082   1.0000000

创建于2022-03-23由reprex包(v2.0.1(

最新更新