【问题标题】:R formule with readLines带有 readLines 的 R 公式
【发布时间】:2013-10-10 09:38:25
【问题描述】:

我是 R 新手,正在尝试使用函数 readLines 制作公式,但 R 一直返回相同的错误并且不知道如何修复它。有什么建议吗?

我的公式

sam.cover<-function(){
     readLines()->CH
     gsub("00","0,0",CH)->CH
     gsub("01","0,1",CH)->CH
     gsub("10","1,0",CH)->CH
     gsub("11","1,1",CH)->CH
     gsub(" 1;","",CH)->CH
     gsub("00","0,0",CH)->CH
     gsub("01","0,1",CH)->CH
     gsub("01","1,0",CH)->CH
     gsub("11","1,1",CH)->CH
     write.table(CH,"temporaryfile.txt",quo=F,sep="",row=F,col=F)
     as.matrix(read.table("temporaryfile.txt",sep=","))->CH
     matrix(CH,nr=dim(CH)[ 1])->CH
     apply(CH,1,sum)->SUM
     CF<-999
     t<-dim(CH)[ 2]
     for(i in 1:t){
         CF<-c(CF,sum(SUM==i))
     }
     cat("Capture frequencies : ","\n")
     print(rbind(1:i,CF[ -1])->CF)
     f1<-CF[ 2,1]
     f2<-CF[ 2,2]
     f3<-CF[ 2,3]
     cat("Sample coverage estimates : ","\n")
     cat("C1-hat =",1-f1/sum(apply(CF,2,prod)),"\n")
     cat("C2-hat =",1-(f1-2*f2/(t-1))/sum(apply(CF,2,prod)),"\n")
     cat("C3-hat =",1-(f1-2*f2/(t-1)+6*f3/(t-1)/(t-2))/sum(apply(CF,2,prod)),"\n")
 }

我的数据

ide    c1   c2  c3  c4  c5
N19 1   1   1   0   1
N29 0   0   1   1   0
N39 0   0   1   0   1
N49 0   0   0   1   1
N59 0   0   1   0   0

我的错误:

Error in readLines(histoire.inp) : 'con' is not a connection

【问题讨论】:

  • 嗨!欢迎来到堆栈溢出。我已经为readLines 提供了答案,但我会问你是否知道read.table,因为你说你是 R 新手。

标签: r readlines


【解决方案1】:

readLines 参数在 connection 上运行,因此如果您想逐行读取文件,您需要做的工作比仅仅提供路径多一点。

首先,您需要为您的文件打开一个connection

conn <- file("histoire.inp", "rt")  # second argument indicates we're reading a text file.

那么,如果你想逐行读取文件,我发现下面的代码块很有用(Original idea here):

while (length(oneLine <- readLines(conn, n = 1, warn = FALSE)) > 0) {
   # Do something to your line of text, stored in `oneLine`
}
close(conn)

如果您想分块读取文件,可以将n 更改为更大的值。

【讨论】:

    猜你喜欢
    • 2014-09-27
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    相关资源
    最近更新 更多