我的原始数据集是
group value
a na
b 1
c 1
c 3
d 2
d 3
我想要一个包含两个新变量的新数据集 - 百分比和比率
group value percent(%) ratio
a na na na
b 1 0 0
c 1 200 3
d 2 50 3/2 =1.5
我可以使用dplyr包来解决问题吗?
答案 0 :(得分:0)
是的,你可以。在以下示例中,dt4
是最终输出。
library(dplyr)
dt <- data_frame(group = c("a", "b", "c", "c", "d", "d"),
value = c(NA, 1, 1, 3, 2, 3))
dt2 <- dt %>%
group_by(group) %>%
filter(n() == 2) %>%
summarise(Value = first(value),
`percent(%)` = (last(value) - first(value))/first(value) * 100,
ratio = last(value)/first(value)) %>%
rename(value = Value)
dt3 <- dt %>%
group_by(group) %>%
filter(n() == 1) %>%
mutate(`percent(%)` = ifelse(is.na(value), NA, 0),
ratio = ifelse(is.na(value), NA, 0))
dt4 <- dt2 %>%
bind_rows(dt3) %>%
arrange(group)