Question: reading txt file
0
gravatar for niutster
19 months ago by
niutster80
niutster80 wrote:

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
txt file R • 572 views
ADD COMMENTlink modified 19 months ago by dariober9.9k • written 19 months ago by niutster80
3
gravatar for dariober
19 months ago by
dariober9.9k
Glasgow - UK
dariober9.9k wrote:

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.

ADD COMMENTlink written 19 months ago by dariober9.9k
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
ADD REPLYlink written 19 months ago by niutster80

It does not work correctly.

ADD REPLYlink written 19 months ago by niutster80

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
ADD REPLYlink written 19 months ago by dariober9.9k
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 963 users visited in the last hour