如何合并/求和给定列中具有相同值的行。然后是直方图。 R工作室
How can I merge / Sum Rows that have the same Value in a given column. Then Histogram. R studio
我正在使用 R studio。
我过滤了一些数据以创建一个只有 2 个变量的新 tibble。
df1 <- df %>% dplyr::select(Species, Weight)
这给了我一些示例数据
Species Weight
1 Dog 7
2 Cat 2
3 Dog 5
4 Dog 4
. . .
. . .
245 Cat 3
246 Dog 9
247 Cat 2
这是一个数据示例,因为我使用的数据实际上包含 25 种鱼类。
我怎样才能将每个物种的权重加在一起,这样我们每一行只有一个物种,如下所示:
Species Weight
1 Dog 734
2 Cat 257
然后我想在直方图中绘制物种与总重量的关系。
任何有关直方图代码的帮助也将不胜感激!
非常感谢。
我们可以按 'Species' 分组,然后在 'Weight' 上执行 sum
,然后用 geom_col
从 ggplot2
[=21 绘制条形图=]
library(dplyr)
df %>%
group_by(Species) %>%
summarise(Weight = log(sum(Weight))) %>%
ggplot(aes(x = Species, y = Weight)) +
geom_col()
或在base R
aggregate(Weight ~ Species, df, sum)
如果我们需要条形图,请使用
barplot(rowsum(df$Weight, df$Species)[,1])
如果我们需要 log
,则用 log
换行
barplot(log(rowsum(df$Weight, df$Species))[,1])
数据
df <- structure(list(Species = c("Dog", "Cat", "Dog", "Dog", "Cat",
"Dog", "Cat"), Weight = c(7L, 2L, 5L, 4L, 3L, 9L, 2L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "245", "246", "247"))
我正在使用 R studio。
我过滤了一些数据以创建一个只有 2 个变量的新 tibble。
df1 <- df %>% dplyr::select(Species, Weight)
这给了我一些示例数据
Species Weight
1 Dog 7
2 Cat 2
3 Dog 5
4 Dog 4
. . .
. . .
245 Cat 3
246 Dog 9
247 Cat 2
这是一个数据示例,因为我使用的数据实际上包含 25 种鱼类。 我怎样才能将每个物种的权重加在一起,这样我们每一行只有一个物种,如下所示:
Species Weight
1 Dog 734
2 Cat 257
然后我想在直方图中绘制物种与总重量的关系。
任何有关直方图代码的帮助也将不胜感激!
非常感谢。
我们可以按 'Species' 分组,然后在 'Weight' 上执行 sum
,然后用 geom_col
从 ggplot2
[=21 绘制条形图=]
library(dplyr)
df %>%
group_by(Species) %>%
summarise(Weight = log(sum(Weight))) %>%
ggplot(aes(x = Species, y = Weight)) +
geom_col()
或在base R
aggregate(Weight ~ Species, df, sum)
如果我们需要条形图,请使用
barplot(rowsum(df$Weight, df$Species)[,1])
如果我们需要 log
,则用 log
barplot(log(rowsum(df$Weight, df$Species))[,1])
数据
df <- structure(list(Species = c("Dog", "Cat", "Dog", "Dog", "Cat",
"Dog", "Cat"), Weight = c(7L, 2L, 5L, 4L, 3L, 9L, 2L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "245", "246", "247"))