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

I have a large dataset that can be represented something like this:

plot 1 2 3 3 3 4 4 5 5 5 5 6 7 fate SMSSMSSSMSSMM 

where the plot is the place, and fate is "survival" or "mortality" (the plant lives or dies). The plot number of the plant corresponds to the fate underneath. 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 proportion of people who survive in each plot for all of these. It is very difficult.

Example: Section 5 will return a survival value of 3/4 or 75%. Section 3 will return a survival value of 2/3 or 66%.

Any help would be greatly 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") 
+2
source share
2 answers

Here is one solution with dplyr ; I created a valu column with 1 if it survived, and 0 if not. After that, this is just the sum of 1 and divides them by the total number of plot elements.

 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 
+1
source

There are many possibilities. Here is 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 
0
source

All Articles