counting the occurrence of substrings in a column in R with group by

前端 未结 2 973
攒了一身酷
攒了一身酷 2021-01-14 03:43

I would like to count the occurrences of a string in a column ....per group. In this case the string is often a substring in a character column.

I have some data e.

2条回答
  •  不思量自难忘°
    2021-01-14 04:26

    You can also use cSplit() from my "splitstackshape" package. Since this package also loads "data.table", you can then just use dcast() to tabulate the result.

    Example:

    library(splitstackshape)
    cSplit(mydf, "String", direction = "long")[, dcast(.SD, village ~ String)]
    # Using 'village' as value column. Use 'value.var' to override
    # Aggregate function missing, defaulting to 'length'
    #    village fd_sec ht_rm san NA
    # 1:       A      1     2   0  1
    # 2:       B      1     0   0  0
    # 3:       C      0     1   1  0
    

提交回复
热议问题