答案 0 :(得分:1)
在dplyr逻辑中有group_by()
,它的工作方式如下:
library(dplyr)
df %>%
group_by(A) %>% # df is now grouped by column A
summarise(Mean = mean(C)) # calculates the mean of C for each group of A, summarise will delete any other columns not summarised and show only distinct rows
df %>%
group_by(A) %>%
mutate(Mean = mean(C)) # This will add the grouped mean to each row without changing the data frame
如果您进行了总结,那么您已经完成了,但是在group_by和mutate之后,您必须ungroup
在某些时候使用数据框。
答案 1 :(得分:0)
data.table示例。在数据中,我们在5个组(组)中有50个观察值(a)。
数据
dt = data.table(
a = runif(1:50),
Group = sample(LETTERS[1:5], 50, replace = T)
)
示例1
首先,我们可以计算a的组均值,如果大于0.5,则标记为“好”,如果小于0.5,则标记为“差”。请注意,此摘要不包含“。”。
dt1 = dt[, .(Mean = mean(a)), keyby = Group][, Label := ifelse(Mean > 0.5, 'Good', 'Bad')]
> dt1
Group Mean Label
1: A 0.2982229 Bad
2: B 0.4102181 Bad
3: C 0.6201973 Good
4: D 0.4841881 Bad
5: E 0.4443718 Bad
示例2
与Fnguyen的答案类似,以下代码不会汇总每组的数据;它只会在每个观察值旁边显示“组均值”和“标签”。
dt2 = dt[, Mean := mean(a), by = Group][, Label := ifelse(Mean > 0.5, 'Good', 'Bad')]
> head(dt2)
a Group Mean Label
1: 0.4253110 E 0.4443718 Bad
2: 0.4217955 A 0.2982229 Bad
3: 0.7389260 E 0.4443718 Bad
4: 0.2499628 E 0.4443718 Bad
5: 0.3807705 C 0.6201973 Good
6: 0.2841950 E 0.4443718 Bad
示例3
最后,我们当然可以应用条件参数来创建新列,而无需事先计算分组变量。以下示例在a和b列上测试组合条件。
dt3 = data.table(a = runif(100), b = runif(100))
dt3[, abGrThan0.5 := ifelse((a > 0.5 & b > 0.5), TRUE, FALSE)]
> head(dt3)
a b abGrThan0.5
1: 0.5132690 0.02104807 FALSE
2: 0.8466798 0.96845916 TRUE
3: 0.5776331 0.79215074 TRUE
4: 0.9740055 0.59381244 TRUE
5: 0.4311248 0.07473373 FALSE
6: 0.2547600 0.09513784 FALSE