前言:
已经1年多没有更新博客了,
似乎工作后时间会越来越少,获取知识的动力和精力有了变化,平凡的普通人大概就是这样吧。
dplyr包补充用到的实用函数:
1、函数cur_group_:数据分组组内标记
- #使用常见的R语言内置数据集iris
- #可以明确的知道当前数据属于哪个分组
- iris %>%
- group_by(Species) %>%
- mutate(group_tag=cur_group_id())
-
- # A tibble: 150 x 6
- # Groups: Species [3]
- Sepal.Length Sepal.Width Petal.Length Petal.Width Species group_tag
- <dbl> <dbl> <dbl> <dbl> <fct> <int>
- 1 5.1 3.5 1.4 0.2 setosa 1
- 2 4.9 3 1.4 0.2 setosa 1
- 3 4.7 3.2 1.3 0.2 setosa 1
-
- #可以明确的知道分组后数据在原始数据所在的行,相当于索引
- iris %>%
- group_by(Species) %>%
- mutate(row_tag= cur_group_rows())
-
- # A tibble: 150 x 6
- # Groups: Species [3]
- Sepal.Length Sepal.Width Petal.Length Petal.Width Species row_tag
- <dbl> <dbl> <dbl> <dbl> <fct> <int>
- 1 5.1 3.5 1.4 0.2 setosa 1
- 2 4.9 3 1.4 0.2 setosa 2
- 3 4.7 3.2 1.3 0.2 setosa 3
-
- #将分组变量以外的数据嵌套起来→相当于dplyr中的group_nest函数
- iris %>%
- group_by(Species) %>%
- summarise(data_tag = list(cur_data()))
-
- # A tibble: 3 x 2
- Species data_tag
- <fct> <list>
- 1 setosa <tibble [50 x 4]>
- 2 versicolor <tibble [50 x 4]>
- 3 virginica <tibble [50 x 4]>
2、快速统计分组数据count、add_count
- #快速计算分组变量标签的行数
- iris %>% count(Species)
-
- Species n
- 1 setosa 50
- 2 versicolor 50
- 3 virginica 50
-
- #灵活计算分组变量指定标签值
- iris %>% add_count(Species, wt = Petal.Length)
-
- Sepal.Length Sepal.Width Petal.Length Petal.Width Species n
- 1 5.1 3.5 1.4 0.2 setosa 73.1
- 2 4.9 3.0 1.4 0.2 setosa 73.1
- 3 4.7 3.2 1.3 0.2 setosa 73.1
- 4 4.6 3.1 1.5 0.2 setosa 73.1
- 5 5.0 3.6 1.4 0.2 setosa 73.1
3、cumall、cumany条件判断为TRUE/FALSE的前后数据过滤
- #计算user_data数据指定条件过滤后按照user_var2排序,再过滤直到第1个user_var3=='y'为TRUE的所有数据
- user_data %>%
- filter(user_var1==x) %>%
- arrange(user_var2) %>%
- filter(cumall(!(user_var3=='y'))) %>%
- summarise(result_tag=max(user_var4))
- 示例:
- iris %>%arrange(Sepal.Width) %>% filter(cumall(!Petal.Length>=5))
-
- Sepal.Length Sepal.Width Petal.Length Petal.Width Species
- 1 5.0 2.0 3.5 1.0 versicolor
- 2 6.0 2.2 4.0 1.0 versicolor
- 3 6.2 2.2 4.5 1.5 versicolor
还没写完!!