edg
edg

Reputation: 353

Changing a list with decimal numbers to numeric

I am new to R and I have problems with converting a list into a numeric object. I have a list of numbers like this

0,4484 0,4495 0,4516 0,4526 0,4533 0,4571 0,4592 0,4625 0,4654 0,4671 0,4686 0,4697

and I want to make a histogram with these values. I read the list into R with:

x <- read.table(as.matrix('foo.txt', sep='\t', header=F)

and it is read as a data.frame. When I try to use hist() on that data.frame it complains about it not being numeric. To convert it to a numeric variable i did this:

as.numeric(c(x[1:1974,])) -> xnum

and it becomes numeric, but when I look at the data in xnum it looks like this

So to extract the numbers and using 'format' to keep the decimal places, I tried this

870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916

I suspected it to be a problem with the decimal numbers, and found that the 'format' function reads numeric values, so I tried this:

format(as.numeric(c(x[1:1974,])), digits=4) -> xnum2

xnum2 then looks like this

"888" "889" "890" "891" "892" "893" "894" "895" "896" "897" "898" "899" "900" "901" "902" "902" "903" "904" "905" "906" "907" "908" "909" "910" "911" "912" "913" "914" "915" "916"

and is no longer numeric!

How can I change the data.frame into an numeric object with decimal places (in order to use hist())?

Upvotes: 0

Views: 3763

Answers (1)

Chase
Chase

Reputation: 69241

As it looks like you figured out, the problem is that R was expecting the decimal separator to be a "." and not a ",". Something like this should get you down the right path:

x <- read.table("foo.txt", sep = "\t", dec = ",", header = FALSE)

Upvotes: 4

Related Questions