Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

r - Frequency of values per column in table

What is a good way to get the independent frequency counts of multiple columns using dplyr? I want to go from a table of values:

# A tibble: 7 x 4
      a     b     c     d
  <int> <int> <int> <int>
1     1     2     1     3
2     1     2     1     3
3     2     2     5     3
4     3     2     4     3
5     3     3     2     3
6     5     3     4     3
7     5     4     2     1

to a frequency table like so:

# A tibble: 5 x 5
      x   a_n   b_n   c_n   d_n
  <int> <int> <int> <int> <int>
1     1     2     0     2     1
2     2     1     4     2     0
3     3     2     2     0     6
4     4     0     1     2     0
5     5     2     0     1     0

I'm still trying to get my head around dplyr, but it seems like this is something it could do. If it is easier to do with an add-on library, that is fine too.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For the same data set that you provided in the question this would be another solution (base-R):

myfreq <- sapply(df, function(x) table(factor(x, levels=unique(unlist(df)), ordered=TRUE)))

Output would be:

> myfreq

#   a b c d 
# 1 2 0 2 1 
# 2 1 4 2 0 
# 3 2 2 0 6 
# 5 2 0 1 0 
# 4 0 1 2 0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...