tags:

views:

67

answers:

2

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!

+2  A: 

Use a=='TRUE'->a.

mbq
This works well when dealing with nonstandard types of logical data; say `'Yes'/'No'`, `7/-5` or just `'true'/'false'`.
mbq
+4  A: 

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

Gavin Simpson
As `what` one could use `NA` cause `typeof(NA)` is `logical`. And for other types special `NA`'s could be used: `NA_integer_`, `NA_real_`, `NA_character_`, `NA_complex_`.
Marek
Or good old `logical(0)`... I think this is the most logical one to use.
mbq
@mbq Your way is better way :)
Marek
@mbq: thanks for that suggestion. I've edited my answer to include mention of this as `logical()` (saves typing one character ;-)
Gavin Simpson