我希望有人能够告诉我从字符向量中提取数据的方法。
数据框如下
structure(list(Sensitivity = structure(c(1L, 5L, 4L, 4L, 4L,
4L, 3L, 5L, 2L), .Label = c(" 1.01 [ 0.21, 2.91]", " 89.60 [ 85.56, 92.82]",
" 92.95 [ 89.43, 95.59]", " 99.66 [ 98.14, 99.99]", " 100.00 [ 98.77, 100.00]"
), class = "factor"), Specificity = structure(c(8L, 1L, 3L, 4L,
2L, 5L, 6L, 1L, 7L), .Label = c(" 27.17 [ 25.15, 29.26]", " 44.96 [ 42.67, 47.26]",
" 53.31 [ 51.00, 55.61]", " 69.90 [ 67.75, 71.99]", " 70.23 [ 68.08, 72.31]",
" 90.18 [ 88.73, 91.50]", " 91.70 [ 90.35, 92.92]", " 100.00 [ 99.80, 100.00]"
), class = "factor")), .Names = c("Sensitivity", "Specificity"
), class = "data.frame", row.names = c(NA, -9L))
作为第一列第一列元素的示例,我理想情况下会得到三列数据:1.01,0.21和2.91。
第一和第二数值由“[”分隔,第二和第三数值由“,”分隔。我不是因为grep而尝试使用而且在某个地方出错了!
答案 0 :(得分:1)
这是一个正则表达式解决方案,您可以尝试使用str_extract_all
stringr
包中的\\d+\\.\\d+
,我们使用.
来匹配从一个或多个数字开始后跟{的十进制数字{1}}和另一个或多个数字模式。
library(stringr)
lapply(df, function(col) do.call(rbind, str_extract_all(col, "\\d+\\.\\d+")))
$Sensitivity
[,1] [,2] [,3]
[1,] "1.01" "0.21" "2.91"
[2,] "100.00" "98.77" "100.00"
[3,] "99.66" "98.14" "99.99"
[4,] "99.66" "98.14" "99.99"
[5,] "99.66" "98.14" "99.99"
[6,] "99.66" "98.14" "99.99"
[7,] "92.95" "89.43" "95.59"
[8,] "100.00" "98.77" "100.00"
[9,] "89.60" "85.56" "92.82"
$Specificity
[,1] [,2] [,3]
[1,] "100.00" "99.80" "100.00"
[2,] "27.17" "25.15" "29.26"
[3,] "53.31" "51.00" "55.61"
[4,] "69.90" "67.75" "71.99"
[5,] "44.96" "42.67" "47.26"
[6,] "70.23" "68.08" "72.31"
[7,] "90.18" "88.73" "91.50"
[8,] "27.17" "25.15" "29.26"
[9,] "91.70" "90.35" "92.92"
答案 1 :(得分:1)
试试这个:
cbind(
matrix(as.numeric(unlist(strsplit(unlist(strsplit(gsub("]","",
dat$Sensitivity), ",")),"\\["))),ncol=3,byrow = T)
,
matrix(as.numeric(unlist(strsplit(unlist(strsplit(gsub("]","",
dat$Specificity), ",")),"\\["))),ncol=3,byrow = T)
)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1.01 0.21 2.91 100.00 99.80 100.00
[2,] 100.00 98.77 100.00 27.17 25.15 29.26
[3,] 99.66 98.14 99.99 53.31 51.00 55.61
[4,] 99.66 98.14 99.99 69.90 67.75 71.99
[5,] 99.66 98.14 99.99 44.96 42.67 47.26
[6,] 99.66 98.14 99.99 70.23 68.08 72.31
[7,] 92.95 89.43 95.59 90.18 88.73 91.50
[8,] 100.00 98.77 100.00 27.17 25.15 29.26
[9,] 89.60 85.56 92.82 91.70 90.35 92.92
答案 2 :(得分:0)
以下是使用base R
提取类型为numeric
lst <- lapply(d1, function(x) read.csv(text=gsub("[][]", ", ", x), header=FALSE)[-4])
lst
#$Sensitivity
# V1 V2 V3
#1 1.01 0.21 2.91
#2 100.00 98.77 100.00
#3 99.66 98.14 99.99
#4 99.66 98.14 99.99
#5 99.66 98.14 99.99
#6 99.66 98.14 99.99
#7 92.95 89.43 95.59
#8 100.00 98.77 100.00
#9 89.60 85.56 92.82
#$Specificity
# V1 V2 V3
#1 100.00 99.80 100.00
#2 27.17 25.15 29.26
#3 53.31 51.00 55.61
#4 69.90 67.75 71.99
#5 44.96 42.67 47.26
#6 70.23 68.08 72.31
#7 90.18 88.73 91.50
#8 27.17 25.15 29.26
#9 91.70 90.35 92.92
如果需要,list
的{{1}}可以通过data.frame
data.frame
cbind