如何从R中的文件中读取逻辑数据

Tim*_*Tim 4 r

我生成了一个文件,每行包含一个"TRUE"或"FALSE"的逻辑值.现在我想将文件中的逻辑数据读入R.但是,读入的数据是模式"字符"而不是逻辑值.我想知道如何从文件中读取数据作为逻辑值.

我的R代码是

cat(FALSE,"\n", file="1.txt", append=FALSE);
for (i in 2:5) cat(TRUE,"\n",file="1.txt", append=TRUE);
a=scan(file="1.txt", what="logical")
Run Code Online (Sandbox Code Playgroud)

输出是:

> mode(a)
[1] "character"
> mode(a[1])
[1] "character"
> a[1]
[1] "FALSE"
Run Code Online (Sandbox Code Playgroud)

我希望[1]成为逻辑值.

感谢致敬!

Rei*_*son 7

啊,现在我明白了.你必须阅读?scan非常仔细一看就知道你做了什么是不是scan()为要what说法.我第一次错过了这个,然后想知道为什么你的代码不起作用.这是关键部分:

what: the type of ‘what’ gives the type of data to be read.  The
      supported types are ‘logical’, ‘integer’, ‘numeric’,
      ‘complex’, ‘character’, ‘raw’ and ‘list’.
Run Code Online (Sandbox Code Playgroud)

关键短语是类型.所以你需要将一个正确类型的对象传递给参数what.

在你的例子中:

> typeof("logical")
[1] "character"
Run Code Online (Sandbox Code Playgroud)

所以scan()读入类型的对象"character".

解决方案只是使用what = TRUE,或者确实是R认为合乎逻辑的任何东西(参见对这个答案的评论)

> typeof(TRUE)
[1] "logical"
> ## or
> typeof(logical())
[1] "logical"

## So now read in with what = TRUE
> a <- scan(file="1.txt", what = TRUE)
Read 5 items
> class(a)
[1] "logical"
> typeof(a)
[1] "logical"
Run Code Online (Sandbox Code Playgroud)

read.table()在如何告诉它要读取的数据方面更合乎逻辑.相应的电话会是:

> b <- read.table("1.txt", colClasses = "logical")[,]
> class(b)
[1] "logical"
> typeof(b)
[1] "logical"
Run Code Online (Sandbox Code Playgroud)

HTH

  • 或者旧的`逻辑(0)`......我认为这是最合乎逻辑的一个. (3认同)