每次向量中的项目属于某个类别时,我可以使用 R 获取类别计数吗?

Can I use R to get a category count for every time an item in a vector pertains to a certain category?

我是 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

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

您可以循环应用 %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()