gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:51:50 28 4
gpt4 key购买 nike

我生成了一个文件,其中每行包含一个“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")

输出是:
> mode(a)
[1] "character"
> mode(a[1])
[1] "character"
> a[1]
[1] "FALSE"

我希望 a[1] 是逻辑值。

感谢致敬!

最佳答案

啊,现在我明白了。您必须阅读?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’.

关键短语是 类型 .所以你需要传递一个正确的对象 类型 争论 what .

在你的例子中:
> typeof("logical")
[1] "character"

所以 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"
read.table()在如何告诉它要读取的数据是什么方面更合乎逻辑。等效的调用将是:
> b <- read.table("1.txt", colClasses = "logical")[,]
> class(b)
[1] "logical"
> typeof(b)
[1] "logical"

HTH

关于r - 如何从R中的文件读取逻辑数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3784617/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com