2017-03-09 36 views
-2

我有一個數據集,其中一列應該是數值,但有些行的值包含關係運算符,如'> ='或'< ='。爲了簡化這一點,考慮我有一個向量:如何將包含關係運算符的字符串向量轉換爲間隔向量?

a <- c('>= 0.99', '0.66', '<= 0.01') 

我應該如何將它轉換爲像間隔的數值向量:

library(intervals) 
b <- Intervals(cbind(left = c(0.99, 0.66, -Inf), right = c(Inf, 0.66, 0.01))) 
b 
# Object of class Intervals 
# 3 intervals over R: 
# [0.99, Inf] 
# [0.66, 0.66] 
# [-Inf, 0.01] 
+0

您的預期產出是多少? – Uwe

+0

它不會保留任何額外的非數字字符和數字 – akrun

+0

請編輯您的問題,並在Q中添加預期的輸出,而不是在評論中。謝謝。 – Uwe

回答

0

我想也許你可以用開關來解決你的問題。

a <- c('>= 0.99', '= 0.66', '<= 0.01') 
oper_num <- matrix(unlist(strsplit(a," "), recursive = T), ncol=2, byrow = T) 
limits <- function(vec){ 
    operation = vec[1] 
    number = vec[2] 
    switch(
    operation, 
    ">=" = paste0("[", number,", Inf]"), 
    ">" =paste0("(", number, ", Inf]"), 
    "=" = paste0("[", number, ", ", number, "]"), 
    "<" = paste0("[-Inf, ", number, ")"), 
    "<=" =paste0("[-Inf, ", number, "]") 
) 
} 
apply(oper_num, 1, limits) 
#> [1] "[0.99, Inf]" "[0.66, 0.66]" "[-Inf, 0.01]" 
0

我們可以使用parse_number

library(readr) 
parse_number(a) 
#[1] 0.51 0.33 0.99 0.66 0.01 
+1

對不起,我編輯了這個問題。但是這個功能真的很方便。 – mt1022

0

隨着正則表達式和函數gsub():

a <- c('.51', '.33', '> .99', '.66', '<= .01') 
a.n <- gsub("<|>|=| ", "", a) 
n <- as.numeric(a.n) 
n 
[1] 0.51 0.33 0.99 0.66 0.01 

請參閱?regexp或gsub獲取更多幫助。

+0

對不起,我編輯了這個問題。 – mt1022

相關問題