Home > Back-end >  read txt file in r always error, how to fix it
read txt file in r always error, how to fix it

Time:06-04

I have a txt file that is like this:

stn;time;rre150m0
APP;200001;59.7
APP;200002;159.3
APP;200003;199.2
APP;200004;82.2
APP;200005;239.6
APP;200006;74.5
APP;200007;332.5
APP;200008;206.9
APP;200210;136.1
APP;200211;206.7
APP;200402;49.6
APP;201006;208.9
APP;201007;272.1
APP;201008;309.1
APP;201009;141.7
BLS;200408;151.7
BLS;200409;138.9
BLS;200810;134.3
BLS;201308;180.9
KRO;200901;45.2
KRO;200902;148.1
KRO;200903;134.4
KRO;200904;31.6
KRO;200905;129.9
KRO;201204;144.5
KRO;201205;132.5
SAE;200202;362.5
SAE;200203;226.1
SAE;200204;174.2
SAE;200205;109.2
SAE;200206;238.3
SAE;200512;271.8
SAE;200601;136.4
SAE;201005;255.0
MMWAA;201910;223.0
MMWAA;201911;105.9
MMWAA;201912;115.4
MMWAA;202001;58.2

I would like to read the file in R but it always throws an error message. I thought that the code for reading that file in R should be like this:

library(readr)
my_data <- read.delim("file.txt", sep =";", header = TRUE, dec =".")

But it doesn't function, then what am I doing wrong?

CodePudding user response:

Use read.table().

read.table("dd.txt",sep=";", header = T,dec =".")
stn   time rre150m0
1    APP 200001     59.7
2    APP 200002    159.3
3    APP 200003    199.2
4    APP 200004     82.2
5    APP 200005    239.6
6    APP 200006     74.5
7    APP 200007    332.5
8    APP 200008    206.9
9    APP 200210    136.1
10   APP 200211    206.7
11   APP 200402     49.6
12   APP 201006    208.9
13   APP 201007    272.1
14   APP 201008    309.1
15   APP 201009    141.7
16   BLS 200408    151.7
17   BLS 200409    138.9
18   BLS 200810    134.3
19   BLS 201308    180.9
20   KRO 200901     45.2
21   KRO 200902    148.1
22   KRO 200903    134.4
23   KRO 200904     31.6
24   KRO 200905    129.9
25   KRO 201204    144.5
26   KRO 201205    132.5
27   SAE 200202    362.5
28   SAE 200203    226.1
29   SAE 200204    174.2
30   SAE 200205    109.2
31   SAE 200206    238.3
32   SAE 200512    271.8
33   SAE 200601    136.4
34   SAE 201005    255.0
35 MMWAA 201910    223.0
36 MMWAA 201911    105.9
37 MMWAA 201912    115.4
38 MMWAA 202001     58.2

CodePudding user response:

Seems to be a problem with your batch file. My suggestion is to replace all spaces with "/n" and the file is read.

Try (e.g in IDLE):

 with open("file_path", "r") as r:
    with open("new_file_path", "w") as w:
        w.write(r.read().replace(' ' , '\n'))

And then:

library(readr)
my_data <- read.delim(file="new_file_path", header=T, sep = ";", dec = ".")

I hope that I helped

  •  Tags:  
  • r
  • Related