簡體   English   中英

與R中的SQL'WHERE'子句類似的函數

[英]Similar function to SQL 'WHERE' clause in R

我有一個數據集分配給一個名為'temps'的變量,它有'date','temperature','country'列。
我想做這樣的事情,我可以在SQL中做

SELECT * FROM temps WHERE country != 'mycountry'

如何在R中進行類似的選擇?

我們可以在base R使用類似的語法

temps[temps$country != "mycountry",]

基准

set.seed(24)
temps1 <- data.frame(country = sample(LETTERS, 1e7, replace=TRUE),
                  val = rnorm(1e7))
system.time(temps1[!temps1$country %in% "A",])
#  user  system elapsed 
#   0.92    0.11    1.04 
system.time(temps1[temps1$country != "A",])
#   user  system elapsed 
#   0.70    0.17    0.88 

如果我們使用包解決方案

library(sqldf)
system.time(sqldf("SELECT * FROM temps1 WHERE country != 'A'"))
#   user  system elapsed 
# 12.78    0.37   13.15 

library(data.table)
system.time(setDT(temps1, key = 'country')[!("A")])
#   user  system elapsed 
#  0.62    0.19    0.37 

這應該做到這一點。

temps2 <- temps[!temps$country %in% "mycountry",]

這里有sqldf和base R方法,其源和樣本輸出基於下面注釋中顯示的輸入。

1)sqldf

library(sqldf)
sqldf("SELECT * FROM temps WHERE country != 'mycountry'")
##   country value
## 1   other     2

2)基地R.

subset(temps, country != "mycountry")
##   country value
## 2   other     2

注意:上面顯示的測試數據如下所示。 下次請求在問題中提供此類可重復的樣本數據。

# test data
temps <- data.frame(country = c("mycountry", "other"), value = 1:2)

暫無
暫無

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

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