2016-10-21 115 views
1

返回的數字我有削減的表像間隔:研究 - 從切

bin targets casos prop phyp  logit 
(-2,-1]  193 6144 0.0314 0 -3.4286244 
    (-1,3]  128 431 0.2970 1 -0.8617025 
(3,11]  137 245 0.5592 1 0.2378497 

我想要得到原來的削減。我試着用:

a<-strsplit(as.character(pl$table[,'bin']), ' ') 

然後我想每一行與分裂:

lapply(a, function(x) strsplit(x, ",")[1]) 

但我沒有得到預期的結果,這就是:

(-1,3,11) 

有更好的方法來實現這一目標?我還需要做些什麼來獲得結果?

感謝。

+1

'不公開(lapply(strsplit(DF $斌, 「」),函數(x)的最大值( as.numeric(gsub(「\\(|]」,「」,x))))' – ytk

回答

1

在你的例子中,有比你所希望檢索的更多的邊界。這會給你所有的界限:

d <- read.table(text=' bin targets casos prop phyp  logit 
"(-2,-1]"  193 6144 0.0314 0 -3.4286244 
    "(1,3]"  128 431 0.2970 1 -0.8617025 
"(3,11]"  137 245 0.5592 1 0.2378497', header=T) 

strings <- as.character(levels(d$bin)) 
strings <- substr(strings, 2, nchar(strings)-1) 
unique(unlist(strsplit(strings, ","))) 
# [1] "-2" "-1" "1" "3" "11" 

如果你只是想的上限,這將工作:

strings <- as.character(levels(d$bin)) 
strings <- sapply(strsplit(strings, ","), function(l){ l[2] }) 
strings <- substr(strings, 1, nchar(strings)-1) 
unique(strings) 
# [1] "-1" "3" "11" 
+0

謝謝,我意識到這一點並在示例中對其進行了更改。 – GabyLP

+0

不客氣,@GabyLP。 – gung

3

如果你的數據是一致的這種格式,你可以使用gsub()

df <- data.frame(bin = c('(-2,-1]','(1,3]','(3,11]'), 
       targets = c(193, 128, 137), 
       casos = c(6144, 431, 245), 
       prop = c(0.0314, 0.297, 0.5592), 
       phyp = c(0,1,1), 
       logit = c(-3.4286244,-0.8617025, 0.2378497), stringsAsFactors = F) 

a <- strsplit(df$bin, ',') 
sapply(a, function(x) gsub("]", "", x))[2,] 
sapply(a, function(x) gsub("\\(", "", x))[1,] 

,讓你

[1] "-1" "3" "11" 
[1] "-2" "1" "3" 
1

另一種方法是:

a<-strsplit(as.character(pl$table[,'bin']), ' ') 
lapply(a, function(x) unlist(strsplit(x, ",|]"))[2])