簡體   English   中英

將R中的特定行添加到新表

[英]get a particular row in R to a new table

我是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

如果有人知道該怎么做,請幫助我。

您可以使用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)工作?

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

數據:

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:如果您在一月份的POSIXlt中獲得data $ Col3 $ mon為0,那么4月為3,而不是您期望的4。 要獲得“正常”月份數,您應該使用month(data $ Col3)-剛意識到要閱讀Ananda的注釋。

如果您想要一個更漂亮的版本(由Ananda Mahto撰寫):

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

    April  July  June 
      2     1     1 

暫無
暫無

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

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