【问题标题】:Can I use R to get a category count for every time an item in a vector pertains to a certain category?每次向量中的项目与某个类别相关时,我可以使用 R 获取类别计数吗?
【发布时间】:2021-04-16 21:54:22
【问题描述】:

我是 R 新手,希望得到帮助:

我想编写一些代码,我可以在其中输入一个向量并确定每个项目属于一个类别的次数。例如,如果我在一个数据框中有三个类别和一个有问题的向量:

```
fruits<-c("Apple","Banana","Pear")
vegetables<-c("Broccoli","Spinach","Peas")
flowers<-c("Rose","Daisy","lily")

df<-cbind(fruits,vegetables,flowers)

df

vectorinquestion<-c("Banana","Peas","Apple")
```

我可以使用什么样的代码来获得输出:

Fruit = 2
Vegetable = 1
Flower = 0

对此的任何帮助将不胜感激!我正在尝试学习新功能,所以这会很有帮助。

【问题讨论】:

    标签: r vector count grouping categories


    【解决方案1】:

    您可以循环应用%in%,创建一个逻辑矩阵。

    
    logical_matrix<-sapply(df, function(x) vectorinquestion %in% x)
    > logical_matrix
         fruits vegetables flowers
    [1,]   TRUE      FALSE   FALSE
    [2,]  FALSE       TRUE   FALSE
    [3,]   TRUE      FALSE   FALSE
    

    然后你可以循环应用一个函数来为每一列求和你的 TRUE:

    > colSums(logical_matrix)
        fruits vegetables    flowers 
             2          1          0 
    

    一站式服务:

    colSums(sapply(df, function(x) vectorinquestion %in% x)
    

    purrr:

    df%>%map(~vectorinquestion %in% .)%>%cbind.data.frame()%>%colSums()
    

    【讨论】:

    • 谢谢,这成功了!我的一个后续问题是如何删除导致 colSum = 0 的列?
    • 为此您可以在代码末尾添加%&gt;% subset(., .!=0)
    • 如:df%&gt;%map(~vectorinquestion %in% .)%&gt;%cbind.data.frame()%&gt;%colSums()%&gt;% subset(., .!=0)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多