Reputation: 1007
I am very new to R and trying to extract a specific element from a data frame and compare it with an integer.
I had a table saved in text file.
I used the following to read the table.
mydata = read.table("file.txt");
In my case I want to compare an element say, say the first element of USERPOR (which is 1.0) with an integer 1.0 (so the comparison should return true).
The code I wrote was
mydata[[2,7]]
[1] 1.000
Levels: 1.000 10.0000 2.000 3.000 4.00 5.00 6.000 7.000 8.000 9.000 USERPROR
However, when I compared them, I got 'FALSE'. Can anybody tell why is that so?
> mydata[[2,7]]==1.0
[1] FALSE
Upvotes: 0
Views: 309
Reputation: 6760
Hmmmm. First, elements of a data.frame are ordinarily accessed using single brackets -- like mydata[2,7]
. Double brackets will access a column, e.g. mydata[[2]]
will return the second column. Thus, mydata[[7]][2]
is the same as mydata[2,7]
.
Second, since your output includes a Levels:
list, it appears that that variable is stored as a factor having levels of "1.000"
, "10.0000"
, ... "USERPROR"
(odd enough that I'm guessing the data are entered incorrectly). Accordingly, I believe that in your example, mydata[2,7] == "1.000"
would return TRUE
.
In general, if you want to compare a numeric value with an integer, don't use a comparison value like 1.0
, because thje .0
part forces it to be stored as floating-point, not integer. If the data are stored as floating-point, there may be enough roundoff that a number computed as 1.0
is not exactly equal to an integer 1
. The reliable way to test it is to use round(mydata[2,7]) == 1
.
Upvotes: 2