0

I wanted to calculate counts of different subsets, which worked fine by using:

count.sur <- aggregate(Survived ~ Child + Sex, test.titanic, FUN = length)

### Child  Sex    Survived
# 1     0 female      142
# 2     1 female       10
# 3     0   male      254
# 4     1   male       12

Then I wanted to calculate the proportions of those counts.

I used this function and added it to my line of code:

    prop.fnc <- function(x){
    results <- count.sur[,3]/sum(count.sur[,3]) 
    return <- results
    }

    aggregate(Survived ~ Child + Sex, test.titanic, prop.fnc)

The values returned were all correct but instead of being organized down a column, they were organized going across the rows and replicated themselves 4 times.

#   Child    Sex Survived.1 Survived.2 Survived.3 Survived.4
# 1     0 female 0.33971292 0.02392344 0.60765550 0.02870813
# 2     1 female 0.33971292 0.02392344 0.60765550 0.02870813
# 3     0   male 0.33971292 0.02392344 0.60765550 0.02870813
# 4     1   male 0.33971292 0.02392344 0.60765550 0.02870813

I'm not sure where I went wrong with the output's format.

Richard Erickson
  • 2,568
  • 8
  • 26
  • 39
bagga1nz
  • 1
  • 1
  • 1
    your example is not [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610), we do not have `test.titanic`, could you paste the result of `dput(test.titanic)` please? – Vincent Bonhomme Mar 30 '16 at 12:24

1 Answers1

0

There are several problems with your function: x is used as an argument, but never used inside the function's body; the last line should be return(results), or just results or you can even remove all results, return and <-.

I don't think you really need an aggregate here, you can simply

count.sur$Survived.prop <- count.sur$Survived / sum(count.sur$Survived)

With a reproducible example:

df <- data.frame(Child=rep(0:1, 2),
                 Sex=rep(c("female", "male"), each=2),
                 Survived=c(142, 10, 254, 12))
df
Child    Sex Survived
1     0 female      142
2     1 female       10
3     0   male      254
4     1   male       12

df$Survived.prop <- with(df, Survived / sum(Survived))
Child    Sex Survived Survived.prop
1     0 female      142    0.33971292
2     1 female       10    0.02392344
3     0   male      254    0.60765550
4     1   male       12    0.02870813

Is that what you wanted to obtain?

Vincent Bonhomme
  • 7,235
  • 2
  • 27
  • 38