示例:
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")
答案 0 :(得分:1)
假设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))