首页 > 解决方案 > 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!

标签: r

解决方案


我们可以使用colSums假设N/ANA

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

如果我们需要改变names

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

的输出colSums是一个命名的vector


推荐阅读