Tim
Tim

Reputation: 99526

How to read logical data from a file in R

I generated a file which contains a logical value either a "TRUE" or a "FALSE" on each line. Now I would like to read the logical data from the file into R. However the data that are read in are of mode "character" not logical values. I was wondering how to read the data as logical values from the file.

My R code is

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")

The output is:

> mode(a)
[1] "character"
> mode(a[1])
[1] "character"
> a[1]
[1] "FALSE"

I want a[1] to be logical value.

Thanks and regards!

Upvotes: 4

Views: 2409

Answers (2)

Gavin Simpson
Gavin Simpson

Reputation: 174898

Ah, now I get it. You have to read ?scan very carefully to see that what you've done is not what scan() wants for the what argument. I missed this first time and then wondered why your code wasn't working. This is the key section:

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’.

and the key phrase is type. So you need to pass an object of the correct type to argument what.

In your example:

> typeof("logical")
[1] "character"

So scan() reads in an object of type "character".

The solution is simply to use what = TRUE, or indeed anything that R considers a logical (see comments to this answer), instead

> 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() is more logical in how you tell it what the data to be read in are. The equivalent call there would be:

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

HTH

Upvotes: 7

mbq
mbq

Reputation: 18628

Use a=='TRUE'->a.

Upvotes: 3

Related Questions