簡體   English   中英

計算符合邏輯標准的觀察次數的最有效方法是什么?

[英]What is the most efficient way to count the number of observations that fit a logical criteria?

使用ggplot2::diamonds數據集,我試圖計算價格低於一定數量的鑽石數量。 我能弄清楚的唯一方法是創建一個新變量並對數據進行子集處理,然后計算新向量中的剩余觀測值。

例:

newVector <- subset(diamonds, price<600)
nrow(newVector)

我想知道解決這個問題的最佳方法是什么? 由於我的方法笨拙。

使用sum

data(diamonds)  # library(ggplot2)
sum(diamonds$price < 600)

另一種使用table

table(diamonds$price < 600)

輸出:

FALSE  TRUE 
49831  4109

使用dplyr

library(dplyr)    
diamonds %>%
      summarise(sum(price < 600))

使用sqldf

library(sqldf)
sqldf("SELECT COUNT(price) 
      FROM diamonds
      WHERE price < 600")

暫無
暫無

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

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