Cuijpie
Cuijpie

Reputation: 33

Count values in column by group R

I want to transform the following dataframe into a dataframe that adds a column of index numbers and counts the values in the rows. Like this:

A  B  C  D  E          value  A  B  C  D  E
1  2  3  4  4              0  2  2  0  1  1
1  4  4  2  1      =>      1  3  0  0  0  2
1  2  2  2  0              2  0  2  2  2  1
0  0  2  0  1              3  0  0  1  1  0
0  0  4  3  2              4  0  1  2  1  1

I am pretty much a beginner in R and can't figure out how to do this. Thanks in advance :)

Upvotes: 0

Views: 110

Answers (1)

jogo
jogo

Reputation: 12559

You can do:

df <- read.table(header=TRUE, text=
"A  B  C  D  E
1  2  3  4  4
1  4  4  2  1
1  2  2  2  0
0  0  2  0  1
0  0  4  3  2")
sapply(df+1, tabulate, nbins=5)
# > sapply(df+1, tabulate, nbins=5)
#      A B C D E
# [1,] 2 2 0 1 1
# [2,] 3 0 0 0 2
# [3,] 0 2 2 2 1
# [4,] 0 0 1 1 0
# [5,] 0 1 2 1 1

Eventually you want correct the rownames:

result <- sapply(df+1, tabulate, nbins=5)
rownames(result) <- (1:nrow(result))-1
result

Upvotes: 4

Related Questions