我试图从文本文件中将数据读入R,以便我可以绘制它:
coupling <- read.table("~/table.format",stringsAsFactors = FALSE, sep='\t')
此表格中的一行如下所示:
133 0.0116, 0.0226, 0.0236, 0.0244, 0.0264, 0.0124, 0.013, 0.014, 0.0158, 0.034, 0.0348, 0.0356, 0.0372 329777.0, -236464.0, -348470.0, -554708.0, -471896.0, 538782.0, 695291.0, 812729.0, 983141.0, 208212.0, 214012.0, 366636.0, 343232.0
其中列(残留,延迟,高度)由制表符分隔,列中的数据由&#39;,&#39;分隔。我现在想绘制高度与延迟,所以我尝试将列分配给变量:
xdata <- c(coupling[1,2])
ydata <- c(coupling[1,3])
但是,如果我尝试绘制情节(xdata,ydata),我会收到以下错误:
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
2: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
3: In min(x) : no non-missing arguments to min; returning Inf
4: In max(x) : no non-missing arguments to max; returning -Inf
5: In min(x) : no non-missing arguments to min; returning Inf
6: In max(x) : no non-missing arguments to max; returning -Inf
打印xdata(和ydata)给出一个形式的变量:
xdata
[1] "0.0116, 0.0226, 0.0236, 0.0244, 0.0264, 0.0124, 0.013, 0.014, 0.0158, 0.034, 0.0348, 0.0356, 0.0372 "
据推测,R不能用引号对此进行绘制。我已经尝试了一些替代方案来尝试绕过这个,但是,这些都没有奏效:
newxdata <-as.numeric(xdata)
返回错误:
Warning message:
NAs introduced by coercion
打印让我接近:
print(xdata,quote=FALSE)
这似乎可以解决问题;输出失去了引号:
[1] 0.0116, 0.0226, 0.0236, 0.0244, 0.0264, 0.0124, 0.013, 0.014, 0.0158, 0.034, 0.0348, 0.0356, 0.0372
但是,如果我将其分配给变量,引号会重新出现,我仍然无法绘制数据:
newxdata <- c(print(xdata,quote=FALSE))
newxdata
[1] "0.0116, 0.0226, 0.0236, 0.0244, 0.0264, 0.0124, 0.013, 0.014, 0.0158, 0.034, 0.0348, 0.0356, 0.0372 "
如何解决这个问题?
答案 0 :(得分:3)
首先需要进行一些修改,然后才能正常工作。引号的原因是你有一个长度为1的字符向量,你需要将其转换为长度为13的数字向量:
#initial data set: character vector of length 1
a <- "0.0116, 0.0226, 0.0236, 0.0244, 0.0264, 0.0124, 0.013, 0.014, 0.0158, 0.034, 0.0348, 0.0356, 0.0372 "
#function to trim leading and trailing spaces **see bottom of answer
trim <- function (x) gsub("^\\s+|\\s+$", "", x)
#first use strsplit to split the long string into separate string elements
#that are comma separated.
#Then use trim on each element to remove leading and trailing spaces
b <- trim(strsplit(a, ',')[[1]])
#finally use as.numeric to convert to numbers
c <- as.numeric(b)
变量c现在可用于绘图
输出:
> c
[1] 0.0116 0.0226 0.0236 0.0244 0.0264 0.0124 0.0130 0.0140 0.0158 0.0340 0.0348 0.0356 0.0372
功能trim
取自here
修改强>
显然根据@ zero323的评论你甚至不需要修剪角色向量。所以,这在一次通话中工作正常:
> as.numeric(strsplit(a, ',')[[1]])
[1] 0.0116 0.0226 0.0236 0.0244 0.0264 0.0124 0.0130 0.0140 0.0158 0.0340 0.0348 0.0356 0.0372
答案 1 :(得分:2)
您也可以使用scan
(来自@ LyzandeR&#39;的数据)
scan(text=a, what=numeric(), sep=",", quiet=TRUE)
#[1] 0.0116 0.0226 0.0236 0.0244 0.0264 0.0124 0.0130 0.0140 0.0158 0.0340
#[11] 0.0348 0.0356 0.0372
您可以直接使用scan
从sep=","
scan("~/table.format", what=numeric(), sep=",", quiet=TRUE) #not tested