每组代表多少个不同的变量?
how many distinct variables are represented in each group?
我有一个这样的数据框:
df <- data.frame(
ID = c('123','124','125','126'),
Group = c('A', 'A', 'B', 'B'),
V1 = c(1,2,1,0),
V2 = c(0,0,1,0),
V3 = c(1,1,0,3))
其中 return 个:
ID Group V1 V2 V3
1 123 A 1 0 1
2 124 A 2 0 1
3 125 B 1 1 0
4 126 B 0 0 3
我想 return 一个 table 指示变量是否在组中表示:
Group V1 V2 V3
A 1 0 1
B 1 1 1
为了统计每组不同变量的个数。
使用:
df %>%
group_by(Group) %>%
summarise_at(vars(V1:V3), funs(as.integer(any(. > 0))))
给出:
# A tibble: 2 × 4
Group V1 V2 V3
<fctr> <dbl> <dbl> <dbl>
1 A 1 0 1
2 B 1 1 1
可以在data.table
完成:
require(data.table)
setDT(df)
table <- df[, .(sum(V1) > 0, sum(V2) > 0, sum(V3) > 0), Group]
table
Group V1 V2 V3
1: A TRUE FALSE TRUE
2: B TRUE TRUE TRUE
table[, lapply(.SD, as.integer), Group, .SD=2:4]
Group V1 V2 V3
1: A 1 0 1
2: B 1 1 1
我有一个这样的数据框:
df <- data.frame(
ID = c('123','124','125','126'),
Group = c('A', 'A', 'B', 'B'),
V1 = c(1,2,1,0),
V2 = c(0,0,1,0),
V3 = c(1,1,0,3))
其中 return 个:
ID Group V1 V2 V3
1 123 A 1 0 1
2 124 A 2 0 1
3 125 B 1 1 0
4 126 B 0 0 3
我想 return 一个 table 指示变量是否在组中表示:
Group V1 V2 V3
A 1 0 1
B 1 1 1
为了统计每组不同变量的个数。
使用:
df %>%
group_by(Group) %>%
summarise_at(vars(V1:V3), funs(as.integer(any(. > 0))))
给出:
# A tibble: 2 × 4
Group V1 V2 V3
<fctr> <dbl> <dbl> <dbl>
1 A 1 0 1
2 B 1 1 1
可以在data.table
完成:
require(data.table)
setDT(df)
table <- df[, .(sum(V1) > 0, sum(V2) > 0, sum(V3) > 0), Group]
table
Group V1 V2 V3
1: A TRUE FALSE TRUE
2: B TRUE TRUE TRUE
table[, lapply(.SD, as.integer), Group, .SD=2:4]
Group V1 V2 V3
1: A 1 0 1
2: B 1 1 1