2014-01-27 64 views
2

我是R新手,所以請指導我。在R中獲得一個特定的行到一個新表

下面顯示了一個簡單的表Order

Col1 Col2 Col3 

    hey hi july 12,2013 
    hey hi june 12,2013 
    hey hi April 12,2013 
    hey hi April 14,2012 

如果我想編寫一個查詢,這樣我得到這個結果作爲一個新的表即。我需要使用正則表達式來匹配Col3中字符串的一部分,然後進行計數。

july  june April 
    1   1  2 

請幫助我,如果有人知道如何做到這一點。

+3

嗯嘗試這個時候你在哪裏卡住? – lukeA

+0

而不是'regexp'如何用'month'來計算,即使用Date函數? –

回答

2

您可以使用sub提取幾個月的姓名和table計數頻率:

dat <- read.table(text = "Col1 Col2 Col3 
hey hi 'july 12,2013' 
hey hi 'june 12,2013' 
hey hi 'April 12,2013' 
hey hi 'April 14,2012'", header = TRUE) 

table(sub("^(\\w+) .*", "\\1", dat$Col3)) 

# April july june 
#  2  1  1 

如何sub("^(\\w+) .*", "\\1", dat$Col3)工作?

函數sub執行字符串中的替換。引號內的字符串是正則表達式。 ^是字符串的開頭,\\w是一個單詞字符,+表示一個或多個。 是一個文字空間。 .*表示任意數量的任何字符。圓括號用於創建組。第一個(也是唯一的)組(\\w+)匹配字符串開頭的單詞字符。 sub函數中的第二個參數"\\1"用於用表示第一組的子字符串替換整個字符串。簡而言之:整個字符串被替換爲第一個單詞。

+0

Thnx,請你解釋一下這個子(「^(\\ w +)。」,「\\ 1」,dat $ Col3)? – Magic

+0

@Magic我添加了一個解釋。 –

+0

太好了!謝謝 – Magic

2

數據:

data <- read.table(text = "Col1 Col2 Col3 
hey hi 'july 12,2013' 
hey hi 'june 12,2013' 
hey hi 'April 12,2013' 
hey hi 'April 14,2012'", header = TRUE) 

的回答使用日期:

#tranform data in POSIXlt  
    data$Col3 <- as.POSIXlt(data$Col3, format="%B %d, %Y") 

    ## group using table with POSIXlt numbers (0 is january) 
    table(data$Col3$mon) 
    3 5 6 
    2 1 1 

    ## group using table with normal month numbers 
    table(month(data$Col3)) 
    4 6 7 
    2 1 1 

    ## group using aggregate with POSIXlt numbers (0 is january) 
    aggregate(data$Col1, by=list(data[,"Col3"]$mon), length) 

    #result 
    Group.1 x 
    1  3 2 
    2  5 1 
    3  6 1 

    ## group using aggregate with normal month numbers 
    aggregate(data$Col1, by=list(month(data$Col3)), length) 

    #result 
    Group.1 x 
1  4 2 
2  6 1 
3  7 1 

PS:磨片,你得到$ COL3 $週一在POSIXlt月份數據爲0,所以四月是3而不是4你會期待。要獲得「正常」的月份數字,您應該使用月份(數據$ Col3) - 剛剛意識到閱讀Ananda的評論。

如果你想有一個更漂亮的版本(由阿難Mahto):

Col3 <- as.POSIXlt(data$Col3, format="%B %d, %Y"); table(month.name[month(Col3)]) 

    April July June 
     2  1  1 
+1

這太漂亮了(我們不必記住POSIXlt的不同來源):'Col3 < - as.POSIXlt(data $ Col3,format =「%B%d,%Y」 );表(month.name [month(Col3)])' – A5C1D2H2I1M1N2O1R2T1

+0

太好了!添加到答案中。 –

+0

剛剛添加Col3 $ mon和月份(Col3)之間的差異,也不知道,感謝評論。 –

相關問題