1
data = data.frame("id"=1:40,
                  "group"=1:5,
                  "score"=sample(1:4,10,r=T))
table(data[which(data$group==1),]$score)
WANT=data.frame("group"=1:5,
                  "score1"=c(0,4,0,4,0),
                  "score2"=c(4,0,0,4,0),
                  "score3"=c(0,4,0,4,0),
                  "score4"=c(0,0,4,4,0))

In data I have "score" but I want to make separate columns for each "score" and then sum up as shown here.

I also want to have my complete data frame 'WANT' and put 0s if there aren't any people but otherwise keep the same structure in terms of rows.

bvowe
  • 3,004
  • 3
  • 16
  • 33
  • Possible duplicate https://stackoverflow.com/questions/8186133/faster-ways-to-calculate-frequencies-and-cast-from-long-to-wide – Ronak Shah Jun 02 '19 at 02:46

1 Answers1

0

An option would be spread after getting the count or frequency by 'group' and 'score'

library(tidyverse)
data %>% 
    count(group, score) %>%
    mutate(score = str_c("score", score)) %>%
    spread(score, n, fill = 0)

If we wanted to have with the all the combinations after the count, use complete

data %>% 
  count(group, score) %>% 
  complete(group, score, fill = list(n = 0))

I also want to have my complete data frame 'WANT' and put 0s if there aren't any people but otherwise keep the same structure in terms of rows.

bvowe
  • 3,004
  • 3
  • 16
  • 33
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks but this just put 1s and eliminated my count values? @akrun – bvowe Jun 02 '19 at 02:42
  • @bvowe No, it is only `fill`ing 0's where there are no combinations, while the count values remain the same. I may be getting a different output from you because there is no set.seed while creating the data – akrun Jun 02 '19 at 02:43
  • Makes sense but now suppose I want to have my complete data frame 'WANT' and put 0s if there aren't any people but otherwise keep the same structure in terms of rows, does that make sense? – bvowe Jun 02 '19 at 02:51
  • I add to my comment that I combine this with the other question you answered good so if there is a better way to combine this with that response please kindly share. – bvowe Jun 02 '19 at 02:52
  • @bvowe Updated the post. But, can you please update your post with the new info as a second piece of info. – akrun Jun 02 '19 at 02:55
  • @akron one more question is if there is a way to efficiently combine this question with my one about the survey weight? – bvowe Jun 02 '19 at 03:29
  • @bvowe I updated in the other post. Also, instead of editing on the answer, can you edit on your question post – akrun Jun 02 '19 at 03:34
  • Error in count(., group, score) : object 'group' not found is an error i am getting now – bvowe Jun 03 '19 at 02:25
  • @bvowe Can you try `data %>% dplyr::count(group, score)` in case you have also loaded another package with `count` – akrun Jun 03 '19 at 03:59