R:我想跳过行但存储一个值

时间:2017-09-28 17:23:46

标签: r

Sample File E:\CPC 091217\091217CPC2.C07
Model 3007
Sample #    1
Start Date  9/12/2017
tart Time   10:28:20
Sample Length   4:16:08
Averaging Interval (secs)   1
Title   
Instrument ID   3007-03160002 3.1
Instrument Errors   None
Mean    17193.2
Min 0
Max 128348
Std. Dev.   11582.1
Time    Concentration (#/cm³)
10:28:21    0
10:28:22    0
10:28:23    0
10:28:24    0

我的文件看起来像这样,我想跳过“Sample File”到“Std.Dev”的所有行,我希望Time和Concentration是标题。但在此之前,我需要将03160002的值(在仪器ID中)存储为A1,稍后在文件名中使用它。我写的是:

    cpcData <- read.csv(cpcFile, sep = ",", dec=".",
                row.names = NULL,header = TRUE,skip=8)
    A1<-cpcData[1,2]
    df = read.csv(cpcData, skip = 6, header = F)

A1很好,但read.csv不再适用于剩下的6行。因为

    Error in read.table(file = file, header = header, sep = sep, quote = quote,  : 
      'file' must be a character string or connection

期待输出:

    Time    Concentration (#/cm³)
    10:28:21    0
    10:28:22    0
    10:28:23    0
    10:28:24    0
    (and A1==03160002)

感谢。

2 个答案:

答案 0 :(得分:0)

您不应该使用read.csv读取包含所需数字的那一行,还有更好的R功能可供阅读。
试试这个。

cpcFile <- "cpcFile.txt"
cpcData <- read.csv(cpcFile, skip = 14)
cpcData
#      Time Concentration....cm3.
#1 10:28:21                     0
#2 10:28:22                     0
#3 10:28:23                     0
#4 10:28:24                     0

txt <- scan(file = cpcFile, what = character(), nmax = 1L, skip = 8L, sep = "\n")
txt <- scan(what = character(), text = strsplit(txt, "-")[[1]][2], nmax = 1L)
txt
#[1] "03160002"

请注意,使用read.csv时,您不需要设置sep = ','dec = '.'header = TRUE。那些已经是默认值 并且执行使用TRUE,而不是T。想象一下有人这样做:T <- FALSE。这完全合法,然后是什么?

答案 1 :(得分:0)

发生此错误是因为您将cpcData作为文件名提供给数据框。我认为你的目的是跳过额外的6行来开始阅读表格部分,但是你不能这样做,因为第一个read.csv调用已经从9日开始读取所有行。

您可以做的是使用skip=14再次读取同一文件,即

df <- read.csv(cpcFile, sep = ",", dec=".",
         row.names = NULL,header = TRUE,skip=14)

作为次要说明,我认为它应该是sep="\t"而不是sep=","。您的文件看起来不像逗号分隔。