簡體   English   中英

R中數據幀的子集

[英]subset of a data frame in R

我有2個數據幀df2DF

> DF
        date tickers
1 2000-01-01       B
2 2000-01-01    GOOG
3 2000-01-01       V
4 2000-01-01    YHOO
5 2000-01-02     XOM

> df2
        date tickers quantities
1 2000-01-01      BB         11
2 2000-01-01     XOM         23
3 2000-01-01    GOOG         42
4 2000-01-01    YHOO         21
5 2000-01-01       V       2112
6 2000-01-01       B         13
7 2000-01-02     XOM         24
8 2000-01-02      BB        422

我需要來自df2的值,這些值存在於DF 這意味着我需要以下輸出:

3 2000-01-01    GOOG         42
4 2000-01-01    YHOO         21
5 2000-01-01       V       2112
6 2000-01-01       B         13
7 2000-01-02     XOM         24

所以我使用了以下代碼:

> subset(df2,df2$date %in% DF$date & df2$tickers %in% DF$tickers)
        date tickers quantities
2 2000-01-01     XOM         23
3 2000-01-01    GOOG         42
4 2000-01-01    YHOO         21
5 2000-01-01       V       2112
6 2000-01-01       B         13
7 2000-01-02     XOM         24

但是輸出包含一個額外的列。這是因為在df2中2天內存在ticker 'xom'。 所以兩行都被選中了。 我的代碼需要進行哪些修改?

輸入如下:

> dput(DF)
structure(list(date = structure(c(1L, 1L, 1L, 1L, 2L), .Label = c("2000-01-01", 
"2000-01-02"), class = "factor"), tickers = structure(c(4L, 5L, 
6L, 8L, 7L), .Label = c("A", "AA", "AAPL", "B", "GOOG", "V", 
"XOM", "YHOO", "Z"), class = "factor")), .Names = c("date", "tickers"
), row.names = c(NA, -5L), class = "data.frame")
> dput(df2)
structure(list(date = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 
2L), .Label = c("2000-01-01", "2000-01-02"), class = "factor"), 
    tickers = structure(c(2L, 5L, 3L, 6L, 4L, 1L, 5L, 2L), .Label = c("B", 
    "BB", "GOOG", "V", "XOM", "YHOO"), class = "factor"), quantities = c(11, 
    23, 42, 21, 2112, 13, 24, 422)), .Names = c("date", "tickers", 
"quantities"), row.names = c(NA, -8L), class = "data.frame")

使用sqldf包:

require(sqldf)

sqldf("SELECT d2.date, d2.tickers, d2.quantities FROM df2 d2 
       JOIN DF d1 ON d1.date=d2.date AND d1.tickers=d2.tickers")

##        date tickers quantities
## 1 2000-01-01    GOOG         42
## 2 2000-01-01    YHOO         21
## 3 2000-01-01       V       2112
## 4 2000-01-01       B         13
## 5 2000-01-02     XOM         24

與我對你的帖子的回答沒有什么不同,但需要稍加修改:

df2[duplicated(rbind(DF, df2[,1:2]))[-seq_len(nrow(DF))], ]

#         date tickers quantities
# 3 2000-01-01    GOOG         42
# 4 2000-01-01    YHOO         21
# 5 2000-01-01       V       2112
# 6 2000-01-01       B         13
# 7 2000-01-02     XOM         24

注意:這為輸出提供了與df2相同的順序。


或者,正如Ben建議的那樣,使用merge

merge(df2, DF, by=c("date", "tickers"))

也會得到相同的結果(但不一定是相同的順序)。

暫無
暫無

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

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