2013-05-13 62 views
1

我有一個矩陣,看起來這艾克:R中的glob2rx獲取所有最後一位小數爲5的單元格?

wun2        308.0  111.0  72.0  64.0 
wupA        8177.0  3933.0  2235.0  2057.0 
wus         5.0  0.0  9.0  5.0 
x16        581.2  154.3  297.1  384.2 
xmas-1        26.5  58.0  26.5  31.0 
xmas-2        201.5  138.2  136.5  203.0 
y         18.0  1.0  13.0  8.0 
yar         5.0  0.0  0.0  2.0 
yata        1283.0  679.0  735.0  784.0 
yellow-b       129.0  82.0  103.0  96.0 
yellow-c       817.3  415.0  832.0  788.0 
zormin       3447.0  2005.0  1999.0  2300.0 
zpg         1.5  0.0  0.0  0.0 
zwilch        1.0  0.0  8.0  14.0 
zye         83.0  64.0  17.0  30.8 

我要四捨五入矩陣,但我希望所有其最後一個小數爲5〜調高至下一個整數的數字。因此,我想在執行一般循環()之前將頂點函數應用於以。(somenumber +)5結尾的所有單元格。

我不知道如何指定作爲外殼表達glob2rx這樣就會使足夠的正則表達式,但我推斷它必須是這樣的:

grx <- "^\\d+\\.\\d+5$" 

然而,這並未當我做grep(grx, x=matrix.1, value=TRUE)時,似乎沒有任何單元格。

什麼可能是錯的?

謝謝! Carmen

+1

你是不是在後''^開始缺少\\? 「^ \\ d \\。\\ d + 5 $」似乎正常工作。 – Arun 2013-05-13 19:28:32

+0

謝謝,阿倫。我已經將這添加到正則表達式中。然而,當我在R中運行它時,作爲'grep(grx,x = WTyoung.WTold,value = TRUE)',我得到:''grep錯誤(grx,x = WTyoung.WTold,value = TRUE) : 無效的正則表達式'^ \ d \。\ 5 $',原因'無效的回參考' – 2013-05-13 19:52:38

回答

3

下面是與基礎R的方式:

d <- read.table(text=" 
    wun2        308.0  111.0  72.0  64.0 
    wupA        8177.0  3933.0  2235.0  2057.0 
    wus         5.0  0.0  9.0  5.0 
    x16        581.2  154.3  297.15  384.2 
    xmas-1        26.5  58.0  26.5  31.0 
    xmas-2        201.5  138.220  136.5  203.0 
    y         18.0  1.0  13.0  8.0 
    yar         5.0  0.0  0.0  2.0 
    yata        1283.0  679.0  735.0  784.0 
    yellow-b       129.0  82.0  103.0  96.0 
    yellow-c       817.345 415.0  832.0  788.0 
    zormin       3447.0  2005.0  1999.0  2300.0 
    zpg         1.0  0.0  0.0  0.0 
    zwilch        1.0  0.0  8.0  14.0 
    zye         83.0  64.0  17.0  30.865") 

subbed <- lapply(d[-1], 
    function(col) ifelse(grepl('\\d+\\.\\d*5$', col), ceiling(col), col)) 
result <- data.frame(d[1], subbed) 


#   V1  V2  V3 V4  V5 
# 1  wun2 308.0 111.00 72 64.0 
# 2  wupA 8177.0 3933.00 2235 2057.0 
# 3  wus 5.0 0.00 9 5.0 
# 4  x16 581.2 154.30 298 384.2 
# 5 xmas-1 27.0 58.00 27 31.0 
# 6 xmas-2 202.0 138.22 137 203.0 
# 7   y 18.0 1.00 13 8.0 
# 8  yar 5.0 0.00 0 2.0 
# 9  yata 1283.0 679.00 735 784.0 
# 10 yellow-b 129.0 82.00 103 96.0 
# 11 yellow-c 818.0 415.00 832 788.0 
# 12 zormin 3447.0 2005.00 1999 2300.0 
# 13  zpg 1.0 0.00 0 0.0 
# 14 zwilch 1.0 0.00 8 14.0 
# 15  zye 83.0 64.00 17 31.0 
+0

這很好用,非常感謝! – 2013-05-13 19:58:11

1

這樣做有幫助嗎?

library(stringr) 

a <- read.table("test.txt") 

apply(a[, 2:ncol(a)], 2, function(x) { 
    w <-str_detect(x, "\\.[0-9]{2,}") & str_sub(x, start=-1) == 5 
    x[w] <- ceiling(x[w]) 
    round(x,2)}) 

      V2  V3  V4  V5 
## [1,] 308.0 111.00 72.0 64.0 
## [2,] 8177.0 3933.00 2235.0 2057.0 
## [3,] 5.0 0.00 9.0 5.0 
## [4,] 581.2 154.30 298.0 384.2 
+0

謝謝,jmsinger! – 2013-05-13 19:57:40

相關問題