我有以下格式的行
IP1:IP2:0.1,0.5,0.9
我使用以下命令拆分此行:
myVector <- (strsplit(oneLine, ":"))
,其中oneline是字符串&#34; IP1:IP2:0.1,0.5,0.9&#34;
我想访问第三列并将其转换为数据框。 我按如下方式访问第三列: listofPValues&lt; - myVector [[1]] [[3]]
listofPValues <- myVector[[1]][[3]]
我正在尝试将listofPValues中的逗号分隔值转换为dataframe,如下所示:
data.frame(as.numeric(listofPValues,',')))
它给了我以下错误
In data.frame(as.numeric(listofPValues, ",")) :
NAs introduced by coercion
我想要使用的功能只接受数据帧。 我想问题是我需要打破字符串&#34; 0.1,0.5,0.9&#34;在我将其转换为数字之前。 如果您有任何建议,请告诉我。
由于 井字游戏
答案 0 :(得分:5)
这是一种使用scan
的方法:
oneLine <- "IP1: IP2: 0.1,0.5,0.9"
myVector <- strsplit(oneLine, ":")
listofPValues <- myVector[[1]][[3]]
listofPValues
# [1] " 0.1,0.5,0.9"
scan(text = listofPValues, sep = ",")
# Read 3 items
# [1] 0.1 0.5 0.9
一个使用strsplit
:
as.numeric(unlist(strsplit(listofPValues, ",")))
# [1] 0.1 0.5 0.9
答案 1 :(得分:3)
您可以使用gregexpr
和regmatches
来提取数字:
as.numeric(unlist(regmatches(oneLine, gregexpr("-?\\d+\\.\\d+", oneLine))))
# [1] 0.1 0.5 0.9