编辑:这是您问题第三版的一个非常优雅的答案:
df <- data.frame(letter = letters, freq = sample(1:100, length(letters)),
stringsAsFactors=F)
df = df %>% group_by(letter) %>% summarize(freq = sum(freq))
df.tots = df %>% group_by(is_vowel = letter %in% c('a','e','i','o','u')) %>%
summarize(freq=sum(freq))
# Now we just rbind your three summary rows onto the df, then pipe it into your ggplot
df %>%
rbind(c('vowels', df.tots[df.tots$is_vowel==T,]$freq)) %>%
rbind(c('consonants', df.tots[df.tots$is_vowel==F,]$freq)) %>%
rbind(c('total', sum(df.tots$freq))) %>%
ggplot( ... your_ggplot_command_goes_here ...)
#qplot(data=..., x=letter, y=freq, stat='identity', geom='histogram')
# To keep your x-axis in order, i.e. our summary rows at bottom,
# you have to explicitly set order of factor levels:
# df$letter = factor(df$letter, levels=df$letter)
注意事项:
- 我们需要
data.frame(... stringsAsFactors=F),所以我们以后可以追加
'vowels', 'consonants', 'total' 行因为这些不会出现
在“字母”的因子水平中
- 请注意,dplyr group_by(is_vowel = ...) 允许我们同时插入一个新列 (
mutate),然后在该表达式 (group_by) 上拆分,所有这些都在一个紧凑的行中。整洁的。从来不知道可以做到这一点。
- 你应该可以让
bind_rows 工作到最后,但我做不到。
编辑:第二个版本。你说你想做一个聚合,所以我们认为每个字母在 df 中都有 >1 条记录。您似乎只是将 df 拆分为元音和辅音,然后再次合并,所以我认为除了is_vowel 之外不需要新的列。一种方法是使用 dplyr:
require(dplyr)
# I don't see why you don't just overwrite df here with df2, the df of totals...
df2 = df %>% group_by(letter) %>% summarize(freq = sum(freq))
letter freq
1 a 150
2 b 33
3 c 54
4 d 258
5 e 285
6 f 300
7 g 198
8 h 27
9 i 36
10 j 189
.. ... ...
# Now add a logical column, so we can split on it when aggregating
# df or df2 ....
df$is_vowel = df$letter %in% c('a','e','i','o','u')
# Then your total vowels are:
df %>% filter(is_vowel==T) %>% summarize(freq = sum(freq))
freq
312
# ... and total consonants ...
df %>% filter(is_vowel==F) %>% summarize(freq = sum(freq))
freq
1011
这是另一种方式,如果您想避免 dplyr,则使用单线:
split(df, df$letter %in% c("a", "e", "i", "o", "u") )
顺便说一句,你可以通过从所有字母中减去元音来更容易地形成辅音列表(/集合):
setdiff(letters, c("a", "e", "i", "o", "u"))
# "b" "c" "d" "f" "g" "h" "j" "k" "l" "m" "n" "p" "q" "r" "s" "t" "v" "w" "x" "y" "z"