This is a test version of Biostars. For the public version, visit https://www.biostars.org.
reading txt file

Hi, I have read a text file by read.delim("Chr.txt), Chr file contains numbers but when i want to get a number and compare , i dont get correct answer:

my_data <- read.delim("Chr.txt")
> my_data[1,1]
[1] 2
Levels: 1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 3 4 5 6 7 8 9 X Y
> my_data[1,1] <3
[1] NA
Warning message:
In Ops.factor(my_data[1, 1], 3) : ‘<’ not meaningful for factors
r txt file

1 answer

This is because my_data[1,1] -> 2 looks like a number but it is not, it's a factor, a label. R read column 1 as factor because you have X and Y that are not numeric.

To convert to numeric use as.numeric(my_data[1,1]). However, I would consider whether it is a meaningful operation to treat chromosome names as numbers.

d=as.numeric(my_data[1,1])
> my_data[1,1]
[1] 2
Levels: 1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 3 4 5 6 7 8 9 X Y
> d
[1] 12

It does not work correctly.

I can reproduce the problem in your original question but not the one here in the comment:

my_data<- data.frame(x= c(2, 3, 1, 'x', 'y'))
my_data[1,1] < 3 # Give NA and Warning

d<- as.numeric(my_data[1,1]) # -> d= 2

d < 3 # -> TRUE

Log in to answer this question.