Home > Software engineering >  how to create a break in a txt file to do a new row in R
how to create a break in a txt file to do a new row in R

Time:04-25

I have a txt file that doesn't have jumps between rows. The txt is like that

ID;YEAR;MOUNT;1D34;2022;1000;2D35;2021;1300

And I need create the data frame in R

ID | YEAR | MOUNT

1D34| 2022 | 1000

2D35| 2021 | 1300

I want to create a new row every 3 elements separated by " ; "

CodePudding user response:

using your data:

txt <- 'ID;YEAR;MOUNT;1D34;2022;1000;2D35;2021;1300'

and base strsplit

matrix(unlist(strsplit(txt_file, ';')), ncol =3, byrow=TRUE)
     [,1]   [,2]   [,3]   
[1,] "ID"   "YEAR" "MOUNT"
[2,] "1D34" "2022" "1000" 
[3,] "2D35" "2021" "1300"

then take to data.frame to further characterize your column data types.

CodePudding user response:

You could do:

read.csv2(text = gsub("(([^;] ;){2}([^;] ));", "\\1\n", readLines('txt.file')))

    ID YEAR MOUNT
1 1D34 2022  1000
2 2D35 2021  1300

CodePudding user response:

If df.txt is your text file, you can do this:

df = strsplit(readLines("df.txt"),";")[[1]]
setNames(as.data.frame(matrix(df[4:length(df)], ncol=3, byrow=T)), df[1:3])

Output:

    ID YEAR MOUNT
1 1D34 2022  1000
2 2D35 2021  1300
  •  Tags:  
  • r
  • Related