gf7
gf7

Reputation: 165

R - New Dataframe from Column Counts?

I have a dataframe that looks like this:

    Dog     Breed     Dog.Distraction     Resource.Guarding
1   Max     BL        N/A                 1
2   Rover   YL        1                   N/A
3   Tina    GR        1                   N/A

I want a new dataframe that looks like:

          Dog. Distraction     Resource.Guarding
Count     2                    1

What's the best way to do this? I can use sum() to find each individual column, but not sure how to convert to new df. Alternatively, I'm also ok with:

                   Count
Dog.Distraction    2
Resource.Guarding  1

Thank you!

Upvotes: 2

Views: 27

Answers (1)

akrun
akrun

Reputation: 887221

We can use colSums assuming the N/A is NA

out <- colSums(df1[c('Dog.Distraction', 'Resource.Guarding')], na.rm = TRUE)

If we need to change the names

names(out) <- c("V1", "V2")

The output of colSums is a named vector

Upvotes: 1

Related Questions