簡體   English   中英

在R中如何計算一個值出現的次數並滿足多個條件

[英]in R how to count the number of times a value appears and meet multiple criteria

例子:

Colour   vehicle      city         type
red       car         London       Petrol
blue      truck       Paris        Diesel
red       car         NewYork      Electric
green     van         Barcelona    Petrol
black     motorbike   LosAngeles   Petrol

即如何計算“汽車”出現的次數,它是“紅色”和“汽油”

這是我試過的

sum(full_data$vehicle == "car" & full_data$Colour == "red" & 
  full_data$type == "Petrol")

假設full_data在最后的 Note 中可full_data顯示,您的代碼對我full_data

# 1
sum(full_data$vehicle == "car" & full_data$Colour == "red" & 
   full_data$type == "Petrol")
## [1] 1

如果問題是如何改進代碼,請嘗試with . 此外,如果數據中有 NA(問題中沒有),我們可以通過在邏輯表達式周圍使用which(...)然后使用length而不是sum來處理它。

# 2
with(full_data, length(which(vehicle == "car" & Colour == "red" & type == "Petrol")))
## [1] 1

這些中的任何一個也可以工作:

# 3
nrow(subset(full_data, vehicle == "car" & Colour == "red" & type == "Petrol"))
## [1] 1

library(dplyr)
full_data %>% 
  filter(vehicle == "car" & Colour == "red" & type == "Petrol") %>%
  nrow
## [1] 1

# 4
library(sqldf)
sqldf('select count(*) as count from full_data 
  where vehicle == "car" and Colour == "red" and type == "Petrol"')
##   count
## 1     1

筆記

full_data <- structure(list(Colour = c("red", "blue", "red", "green", "black"
), vehicle = c("car", "truck", "car", "van", "motorbike"), city = c("London", 
"Paris", "NewYork", "Barcelona", "LosAngeles"), type = c("Petrol", 
"Diesel", "Electric", "Petrol", "Petrol")), class = "data.frame", row.names = c(NA, 
-5L))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM