簡體   English   中英

根據條件是否適用於R中的每一行從矩陣中提取行

[英]Extract rows from matrix based on if condition applied to each row in R

您能幫我弄清楚為什么以下方法不起作用嗎? 我有一個2528x3的矩陣uniqueitems,看起來像這樣:

Number        Created               Customer
===========   ===================   ============
31464686486   2013-10-25 10:00:00   john@john.de
...

我想做的是:遍歷每一行,檢查Created是否比給定時間更新,如果是,則將該行寫到newtablethantable的新表中。 這是我的代碼:

library(lubridate);
newerthan <- function(x) {
  times <- ymd_hms(uniqueitems[,2])
  newerthantable <- matrix(data=NA,ncol=3,nrow=1)
  i <- 1;
  while (i <= nrow(uniqueitems)) {
    if (x < times[i]) {
      newerthantable <- rbind(newerthantable,uniqueitems[i,])
    }
    i <- i + 1;
  }
}

但是newerthan(“ 2013-10-24 14:00:00”)並沒有達到預期的效果:(,newerthantable中沒有任何內容。為什么?

在R中很少需要循環。 使用矢量化操作或子集可以達到與這種情況相同的結果。

設置樣本數據框:

number <- c(1:10)
created <- seq(as.POSIXct("2013-01-01 10:01"), length.out=10, by="26 hours")
customer <- letters[c(1:10)]
df <- data.frame(number, created, customer)

head(df, 10)

   number             created customer
1       1 2013-01-01 10:01:00        a
2       2 2013-01-02 12:01:00        b
3       3 2013-01-03 14:01:00        c
4       4 2013-01-04 16:01:00        d
5       5 2013-01-05 18:01:00        e
6       6 2013-01-06 20:01:00        f
7       7 2013-01-07 22:01:00        g
8       8 2013-01-09 00:01:00        h
9       9 2013-01-10 02:01:00        i
10     10 2013-01-11 04:01:00        j

選擇比給定日期新的行:

newerthantable <- df[df$created > as.POSIXct("2013-01-05 18:01:00"), ]

head(newerthantable,10)

   number             created customer
6       6 2013-01-06 20:01:00        f
7       7 2013-01-07 22:01:00        g
8       8 2013-01-09 00:01:00        h
9       9 2013-01-10 02:01:00        i
10     10 2013-01-11 04:01:00        j

方括號選擇符合我們條件的行( created列大於給定日期)和所有列(逗號后沒有列說明)。 在此處閱讀有關子設置操作的更多信息: http : //www.ats.ucla.edu/stat/r/modules/subsetting.htm

如果要將其包裝為一個函數,它將如下所示:

new_entries <- function(data, rows_since){

  data[data$created > as.POSIXct(rows_since), ]

}

new_entries(df, "2013-01-05 18:01:00")

暫無
暫無

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

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