我有一个数据框:
role <- c("hi", "hi", "lo", "lo", "me", "me")
a <- c("w", "r","w", "r", "w", "r")
b <- c("z", "x","z", "x", "z", "x")
c <- c("o", "o","p", "p", "t", "y")
df <- data.frame(role, a, b, c)
要获取数据透视表样式摘要,其中role
具有a
列中因子的频率,我使用dplyr:
summ <- df %>%
group_by(role, a) %>%
tally() %>%
spread(a, n, fill = 0)
summ
如何使用一个dplyr管道为所有列(a
,b
和c
)自动生成单独的数据透视表?
答案 0 :(得分:3)
以下是使用tidyverse
library(tidyverse)
names(df)[-1] %>%
map(~df %>%
select(.x, role) %>%
group_by(!!sym(.x), role) %>%
tally() %>%
spread(!!sym(.x), n, fill = 0))
# [[1]]
# A tibble: 3 x 3
# role r w
#* <fctr> <dbl> <dbl>
#1 hi 1 1
#2 lo 1 1
#3 me 1 1
#[[2]]
# A tibble: 3 x 3
# role x z
#* <fctr> <dbl> <dbl>
#1 hi 1 1
#2 lo 1 1
#3 me 1 1
#[[3]]
# A tibble: 3 x 5
# role o p t y
#* <fctr> <dbl> <dbl> <dbl> <dbl>
#1 hi 2 0 0 0
#2 lo 0 2 0 0
#3 me 0 0 1 1
答案 1 :(得分:2)
一种方法,保留您用于单个数据透视表的代码:
library(dplyr); library(tidyr)
df %>%
gather(key, value, -role) %>%
split(.$key) %>%
lapply(function(x){x %>% group_by(role, value) %>%
tally() %>%
spread(value, n, fill = 0)})
$a
# A tibble: 3 x 3
# Groups: role [3]
role r w
* <chr> <dbl> <dbl>
1 hi 1 1
2 lo 1 1
3 me 1 1
$b
# A tibble: 3 x 3
# Groups: role [3]
role x z
* <chr> <dbl> <dbl>
1 hi 1 1
2 lo 1 1
3 me 1 1
$c
# A tibble: 3 x 5
# Groups: role [3]
role o p t y
* <chr> <dbl> <dbl> <dbl> <dbl>
1 hi 2 0 0 0
2 lo 0 2 0 0
3 me 0 0 1 1
答案 2 :(得分:1)
对于基数为R的lapply
和table
:
lapply(df[-1], function(x) table(df$role, x))
$a
x
r w
hi 1 1
lo 1 1
me 1 1
$b
x
x z
hi 1 1
lo 1 1
me 1 1
$c
x
o p t y
hi 2 0 0 0
lo 0 2 0 0
me 0 0 1 1
返回表对象列表。如果你想要一个data.frames列表,你可以做
lapply(df[-1], function(x) as.data.frame.matrix(table(df$role, x)))
答案 3 :(得分:0)
仅供参考您还使用// template
<div class="form-group">
<select formControlName="category">
<option [ngValue]="null">Select Category</option>
<option *ngFor="let option of options"
[ngValue]="option">{{option.label}}</option>
</select>
</div>
// component
options = [{ id: 1, label: 'Category One' }, { id: 2, label: 'Category Two' }];
form = new FormGroup({
category: new FormControl(null, Validators.required)
});
进行收集,您可以使用tidyr
代替count
,然后使用group
来获得更简洁的数据。
如果您想要一张表概述所有组合的表:
tally