Search code examples
rcountrbind

How do I create a row in R with each row element equal to the number of values in its column?


I was thinking of maybe using two of the following concepts: 1. rbind 2. some sort of thing like COUNT in SQL

Imagine table X:

[A · B  · C ]
[1 · 2  · 3 ]
[3 · NA · 4 ]
[6 · NA · NA]

With the addition of a new row, my new table X(1) would look like:

[A · B  · C ]
[1 · 2  · 3 ]
[3 · NA · 4 ]
[6 · NA · NA]
[3 · 1  · 2 ]

With the [3 · 1 · 2] signifying the number of elements above itself.


Solution

  • You can use a combination of rbind and rowSums of non-NA values. See below.

    Also for future reference if you provide data in a more easily reproducible format it is more helpful. For example how I have below or for more complicated data you can run dput(X) and post the output that is returned

    X <- data.frame(A = c(1,3,6), B = c(2,NA,NA), C = c(3,4,NA))
    
    rbind(X, rowSums(!is.na(X)))
    #>   A  B  C
    #> 1 1  2  3
    #> 2 3 NA  4
    #> 3 6 NA NA
    #> 4 3  2  1
    

    Created on 2020-03-24 by the reprex package (v0.3.0)