Creating Percentages instead of Sums using melt/cast
r
Solution
Seems hard to me to avoid doing this in two steps. The problem is that you want to run the cumsum/sum function on the output of the dcast operation, unless I'm misunderstanding what you want still.
First is as you have it:
eg.c <- dcast(eg.m,Time ~ variable, sum )
Second is just applying the cumsum/sum function to the columns:
japply(eg.c, sapply(eg.c, is.numeric ), function(x) cumsum(x)/sum(x) )
Time A1 A2 B1
1 1 0.5 0.5 NaN
2 2 1.0 1.0 NaN
Where `japply` is a function I have in my .RProfile:
# Takes a data.frame and returns a data.frame with only the specified columns transformed
japply <- function(df, sel, FUN=function(x) x, ...) {
df[,sel] <- sapply( df[,sel], FUN, ... )
df
}
Problem
Simple example. I would like to create a data frame of percentages using cast/melt instead of sums. Example. ``` eg <- data.frame( Time = factor(c(1,2,1,2)), A1 = c(0, 0, 1, 1), A2 = c(1, 1, 1, 1), B1 = c(0, 0, 0, 0) ) eg.m <- melt(eg,id="Time") eg.c <- cast(eg.m,Time ~ variable, sum, margins="grand_row") ``` In the above example, I can produce the sum and total. Rather than produce the sum, is there a means to produce the percentage in each cell, i.e. sum of cell / gran_row? I know I can do some stuff here using ddply and reshape, but wondering if there is a more elegant solution. Here's an example of what I'm looking for: ``` Time A1 A2 B1 1 1 0.5 0.5 0 2 2 1.0 1.0 0 ```