Calculate relative frequency of list terms and its sum in R?

泄露秘密 提交于 2019-12-11 06:23:37

问题


I have data saved in a long list. This is an example of the first six lines / records:

A <- list(c("JAMES","CHARLES","JAMES","RICHARD"),  
    c("JOHN","ROBERT","CHARLES"),  
    c("CHARLES","WILLIAM","CHARLES","MICHAEL","WILLIAM","DAVID","CHARLES","WILLIAM"),  
    c("CHARLES"),  
    c("CHARLES","CHARLES"),  
    c("MATTHEW","CHARLES","JACK"))  

Now I would like to calculate the relative frequency with which each unique term occurs in each line / record.
Based on my example I would like to achieve an output similar to this:

[1] "JAMES" 0.5 "CHARLES" 0.25 "RICHARD" 0.25  
[2] "JOHN" 0.3333333 "ROBERT" 0.3333333 "CHARLES" 0.3333333  
[3] "CHARLES" 0.375 "WILLIAM" 0.375 "MICHAEL" 0.125 "DAVID" 0.125  
[4] "CHARLES" 1  
[5] "CHARLES" 1  
[6] "MATTHEW" 0.3333333 "CHARLES" 0.3333333 "JACK" 0.3333333  

So far I only know how to calculate the relative frequency of individual terms, unfortunately; e.g.:

> (sapply(A, function(x)sum(grepl("JAMES", x))))/sapply(A, length)  
[1] 0.5 0.0 0.0 0.0 0.0 0.0  

My example contains only ten unique terms, of course. But my actual data contains almost 200 unique terms so the approach above wouldn't be feasible. Therefore I'm looking for a different way which would allow me to calculate the relative frequency of all of the terms in just one go, please.
In addition to that I would like to sum up these relative frequencies for each unique name over all lines / records.
Based on my example above I would like to achieve an output similar to this one, please:

[1] "JAMES" 0.5  
[2] "CHARLES" 3.291667  
[3] "RICHARD" 0.25  
[4] "JOHN" 0.3333333  
[5] "ROBERT" 0.3333333  
[6] "WILLIAM" 0.375  
[7] "MICHAEL" 0.125  
[8] "DAVID" 0.125  
[9] "MATTHEW" 0.3333333  
[10] "JACK" 0.3333333  

Thank you very much in advance for your consideration!


回答1:


You could use ?table and ?aggregate:

BL <- lapply(A, function(x)table(x)/length(x))
## turn list into a vector
B <- unlist(BL)

## sum all frequencies
aggregate(B, list(names(B)), FUN=sum)
#   Group.1         x
#1  CHARLES 3.2916667
#2    DAVID 0.1250000
#3     JACK 0.3333333
#4    JAMES 0.5000000
#5     JOHN 0.3333333
#6  MATTHEW 0.3333333
#7  MICHAEL 0.1250000
#8  RICHARD 0.2500000
#9   ROBERT 0.3333333
#10 WILLIAM 0.3750000



回答2:


I think this is what you want:

lapply(A,function (x) table(x)/length(x))


来源:https://stackoverflow.com/questions/11546941/calculate-relative-frequency-of-list-terms-and-its-sum-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!