R - New Dataframe from Column Counts?

Viewed 21

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!

1 Answers

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

Related