Gerrit
Gerrit

Reputation: 2677

Build sum of column occurence in R?

I do my first steps with R and try to convert a data frame from this format:

  org_unit answer
1     4712     75
2     4713     50
3     4712     75
4     4713     50
5     4712     25

To this format

  org_unit 100  75  50  25   0
1     4712   0   2   0   1   0
2     4713   0   0   2   0   0

Valid column values of answer are 100, 75, 50, 25, 0.

Thanks!

Upvotes: 0

Views: 44

Answers (2)

lmo
lmo

Reputation: 38500

You can also use xtabs:

xtabs(~org_unit + answer, data=df)
       answer
org_unit 25 50 75
    4712  1  0  2
    4713  0  2  0

To produce a data.frame from this, use

data.frame(rbind(dfNew))
     X25 X50 X75
4712   1   0   2
4713   0   2   0

Upvotes: 1

akrun
akrun

Reputation: 886938

We can use table after converting the 'answer' to factor with levels specified.

df$answer <- factor(df$answer, levels = c(100, 75, 50, 25, 0))
table(df)
#          answer
# org_unit 100 75 50 25 0
#     4712   0  2  0  1 0
#     4713   0  0  2  0 0

Upvotes: 3

Related Questions