假设一个向量包含如下的置信区间
confint <- c("[0.741 ; 2.233]", "[263.917 ; 402.154]", "[12.788 ; 17.975]", "[0.680 ; 2.450]", "[0.650 ; 1.827]", "[0.719 ; 2.190]")我想要两个新的向量,一个包括数值格式的下限,如
lower <- c(0.741, 263.917, 12.788, 0.680, 0.650 , 0.719)并包括数值格式的上限,如
upper <- c(2.233, 402.154, 17.975, 2.450, 1.827, 2.190)发布于 2019-05-27 12:41:31
基R解
lower = as.numeric(sub(".*?(\\d+\\.\\d+).*", "\\1", confint))
upper = as.numeric(sub(".*\\b(\\d+\\.\\d+).*", "\\1", confint))
lower
[1] 0.741 263.917 12.788 0.680 0.650 0.719
upper
[1] 2.233 402.154 17.975 2.450 1.827 2.190发布于 2019-05-27 12:52:19
mypattern <- '\\[(\\d+\\.\\d+) ; (\\d+\\.\\d+)\\]'
as.numeric(gsub(mypattern, '\\1', confint))
as.numeric(gsub(mypattern, '\\2', confint))发布于 2019-05-27 12:49:23
另一种base R可能是:
sapply(strsplit(confint, " ; ", fixed = TRUE), function(x) gsub("[^0-9.-]+", "\\1", x) [1])
sapply(strsplit(confint, " ; ", fixed = TRUE), function(x) gsub("[^0-9.-]+", "\\1", x) [2])
[1] "0.741" "263.917" "12.788" "0.680" "0.650" "0.719"
[1] "2.233" "402.154" "17.975" "2.450" "1.827" "2.190" 如果您需要它作为一个数字向量:
sapply(strsplit(confint, " ; ", fixed = TRUE), function(x) as.numeric(gsub("[^0-9.-]+", "\\1", x)) [1])
sapply(strsplit(confint, " ; ", fixed = TRUE), function(x) as.numeric(gsub("[^0-9.-]+", "\\1", x)) [2])https://stackoverflow.com/questions/56326130
复制相似问题