How to make an average of a variable assigned to individuals within a category?

妖精的绣舞 提交于 2020-01-15 07:18:11

问题


I have a big data set which could be represented something like this:

plot 1 2 3 3 3 4 4 5 5 5 5 6 7
fate S M S S M S S S M S S M M

where plot is a location, and fate is either "survivorship" or "mortality" ( a plant lives or dies.) The plot number of a plant corresponds to the fate under it. Thus in plot 5 there are 4 plants. 3 of them survive, 1 dies.

I want to figure out a way to make R calculate the fraction of individuals that survive in each plot for all of these. It is proving very challenging.

Example: Plot 5 would return a survivorship value of 3/4 or 75% Plot 3 would return a survivorship value of 2/3 or 66%

Any help would be much appreciated. Thank you

Data

structure(list(plot = c(1, 2, 3, 3, 3, 4, 4, 5, 5, 5, 5, 6, 7
), fate = structure(c(2L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 
2L, 1L, 1L), .Label = c("M", "S"), class = "factor")), .Names = c("plot", 
"fate"), row.names = c(NA, -13L), class = "data.frame")

回答1:


Here is one solution with dplyr; I've created valu column with 1 if survived and 0 if not. After that it is only a matter of sum the 1's and divide them by the total number of elements of plot.

library(dplyr)
df %>% group_by(plot) %>%
       mutate(valu = ifelse(fate == "S", 1, 0)) %>%
       mutate(perce = (sum(valu)/n() )*100 )

Source: local data frame [13 x 4]
Groups: plot

   plot fate valu     perce
1     1    S    1 100.00000
2     2    M    0   0.00000
3     3    S    1  66.66667
4     3    S    1  66.66667
5     3    M    0  66.66667
6     4    S    1 100.00000
7     4    S    1 100.00000
8     5    S    1  75.00000
9     5    M    0  75.00000
10    5    S    1  75.00000
11    5    S    1  75.00000
12    6    M    0   0.00000
13    7    M    0   0.00000



回答2:


There are many possibilities. Here's one:

plot <- c(1,2,3,3,3,4,4,5,5,5,5,6,7)
fate <- as.factor(c("S","M","S","S","M","S","S","S","M","S","S","M","M"))
sapply(lapply(split(fate, plot), function(x) round(prop.table(table(x))*100, 2 )), "[", "S")
#   1.S    2.S    3.S    4.S    5.S    6.S    7.S 
# 100.00   0.00  66.67 100.00  75.00   0.00   0.00 


来源:https://stackoverflow.com/questions/31439306/how-to-make-an-average-of-a-variable-assigned-to-individuals-within-a-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!