Given a small dataset as follows:
df <- structure(list(id = 1:8, type = structure(c(1L, 1L, 1L, 2L, 2L,
3L, 3L, 3L), .Label = c("a", "b", "c"), class = "factor"), values = c(360000L,
331715L, 260000L, 164900L, NA, 120000L, 331238L, 629861L)), class = "data.frame", row.names = c(NA,
-8L))
How could I groupby type
and sum up values
and count numbers of entries, then calculate value_percent
and number_percent
for each type
?
The expected result will like this:
Thanks for your help at advance.
Update:
value_percent
become all 1
s if Chinese characters inside dataset for @Karthik S's solution.
df <- structure(list(物业类型 = structure(c(1L, 3L, 2L, 1L, 3L,
4L, 3L, 3L, 4L, 4L, 4L, 3L), .Label = c("商业/零售", "数据中心",
"写字楼", "综合体"), class = "factor"), 成交总价.万元. = c(360000L,
331715L, 260000L, 164900L, NA, 120000L, 331238L, 629861L, 68800L,
47600L, 804600L, 450000L)), class = "data.frame", row.names = c(NA,
-12L))
Code:
df %>%
group_by(物业类型) %>%
dplyr::summarise(总额占比 = sum(成交总价.万元., na.rm = T)/sum(成交总价.万元., na.rm = T), 笔数占比 = n()/nrow(df))
Out: