-1

Similar to this question Count number of observations/rows per group and add result to data frame but not quite.

I'd like to transform this

   group id_in_group letter
1:     A          A1   alef
2:     A          A2    bet
3:     A          A3    bet
4:     B          B1   alef
5:     B          B2   alef
6:     B          B3  gimel

into this

   group aleph bet gimel
1:     A     1   2     0
2:     B     2   0     1
Community
  • 1
  • 1
fschr
  • 1
  • 1

3 Answers3

4

Or without any additional library, you can just use table:

table(df$group,df$letter)

As you seem to work with data.table, you can also use dcast()

dcast(df, group~letter,length)
xraynaud
  • 2,028
  • 19
  • 29
3

Tipical task I'd perform using dplyr and tidyr.

library(dplyr)
library(tidyr)
df <- data.frame(group = c("A", "A", "A", "B", "B", "B"),
             id_in_group = c("A1", "A2", "A3", "B1", "B2", "B3"),
             letter = c("alef", "bet", "bet", "alef", "alef", "gimel"))

df %>% 
  group_by(group, letter) %>% 
  summarise(n = n()) %>% 
  spread(letter, n, fill = 0)
jess
  • 534
  • 2
  • 7
  • 1
    Alternatively you could do: `... %>% group_by(group) %>% count(letter) %>% ...` – Thomas K Mar 28 '17 at 14:36
  • 4
    @ThomasK No need for group_by, apparently: `DF %>% count(group, letter) %>% spread(letter, n, fill = 0)` – Frank Mar 28 '17 at 15:24
-1

With data.table

library(data.table)

dt <- data.table(group=c(rep('A',3),rep('B',3)),
           id_in_group=c(paste0('A',seq(1,3,1)),paste0('B',seq(1,3,1))),
           letter=c('alef','bet','bet','alef','alef','gimel'))

dt[,aleph:=ifelse(like(letter,"a"),1,0)][
  ,bet:=ifelse(like(letter,"bet"),1,0)][
  ,gimal:=ifelse(like(letter,"gimel"),1,0)]
dt[,':='(id_in_group=NULL,letter=NULL)][,lapply(.SD,sum),by=group]
jg_r
  • 81
  • 5