问题
创建包含百分比的新行
数据
df<- data.frame(
species = c ("A","A","A","A","B","B","B","B","A","A","A","A","B","B","B","B"),
number = c(1,1,2,2,1,1,2,2,1,1,2,2,1,1,2,2),
treatment = c(0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1),
variable = c ("x","y","x","y","x","y","x","y","x","y","x","y","x","y","x","y"),
value = sample(1:16)
)
问题
我想计算给定数量和处理的物种的百分比。即变量x和y(第一行)的总和应为100%。
我试过用dplyr:
result <- df%>%
group_by(variable) %>%
mutate(percent = value*100/sum(value))
test<-subset(result,variable=="x")
sum(test[,6])
“测试”是错误的,因为它是两个物种和两种处理的所有x的百分比。
期望输出
species number treatment variable value percent
A 1 0 x 40 40
A 1 0 y 60 60
A 2 0 x 1 10
A 2 0 y 9 90