从R中的文本文件中提取一行数值
extracting a line of numerical values from text file in R
问题:
我需要从文本文件中提取数值并将字符串转换为数值。
例如,在我的文本文件中:
亚达亚达亚达...
基频:0.247 0.355 0.158 0.261
等等等等...
alpha[0]: 0.466477 rates[0] ac ag at cg ct gt: 0.0987 2.4837 0.4734 0.4902 0.2713 1.0000
更多字...
文本文件结束。
我需要退出:
base(一个向量,应该是(0.247,0.355,0.158,0.261))
alpha(一个应该等于 0.466477 的变量)
rates(一个向量应该等于(0.0987,2.4837,0.4734,0.4902))
我做了什么
library(tm)
#Read in text file
myfile <- "RAxML_info.gtr1"
mdata <- readLines(my file)
cline <- grep("Base frequencies:",mdata,value=TRUE)
as.vector(gsub("Base frequencies: ", "", cline))
[1] "0.247 0.335 0.158 0.261 "
这只是作为一个字符串处理,我无法将其作为数值向量。
使用 RStudio 和 R 版本 3.3.1
根据@HubertL 的评论,您可以使用 strsplit
从您所在的位置到达您想要的位置:
line <- "0.247 0.335 0.158 0.261 "
line <- strsplit( line, split = " " )[[1]]
line <- as.numeric( line )
line
[1] 0.247 0.335 0.158 0.261
output <- "0.247 0.335 0.158 0.261 "
as.numeric(unlist(strsplit(output, " ")))
[1] 0.247 0.335 0.158 0.261
我们可以使用scan
scan(text=output, what = numeric(), quiet=TRUE)
#[1] 0.247 0.335 0.158 0.261
数据
output <- "0.247 0.335 0.158 0.261 "
问题: 我需要从文本文件中提取数值并将字符串转换为数值。
例如,在我的文本文件中:
亚达亚达亚达...
基频:0.247 0.355 0.158 0.261
等等等等...
alpha[0]: 0.466477 rates[0] ac ag at cg ct gt: 0.0987 2.4837 0.4734 0.4902 0.2713 1.0000
更多字... 文本文件结束。
我需要退出: base(一个向量,应该是(0.247,0.355,0.158,0.261)) alpha(一个应该等于 0.466477 的变量) rates(一个向量应该等于(0.0987,2.4837,0.4734,0.4902))
我做了什么
library(tm)
#Read in text file
myfile <- "RAxML_info.gtr1"
mdata <- readLines(my file)
cline <- grep("Base frequencies:",mdata,value=TRUE)
as.vector(gsub("Base frequencies: ", "", cline))
[1] "0.247 0.335 0.158 0.261 "
这只是作为一个字符串处理,我无法将其作为数值向量。
使用 RStudio 和 R 版本 3.3.1
根据@HubertL 的评论,您可以使用 strsplit
从您所在的位置到达您想要的位置:
line <- "0.247 0.335 0.158 0.261 "
line <- strsplit( line, split = " " )[[1]]
line <- as.numeric( line )
line
[1] 0.247 0.335 0.158 0.261
output <- "0.247 0.335 0.158 0.261 "
as.numeric(unlist(strsplit(output, " ")))
[1] 0.247 0.335 0.158 0.261
我们可以使用scan
scan(text=output, what = numeric(), quiet=TRUE)
#[1] 0.247 0.335 0.158 0.261
数据
output <- "0.247 0.335 0.158 0.261 "