how to create a break in a txt file to do a new row in R

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 " ; "

Upvotes: 1

Views: 67

Answers (3)

Onyambu
Onyambu

Reputation: 79228

You could do:

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

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

Upvotes: 0

langtang
langtang

Reputation: 24722

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

Upvotes: 0

Chris
Chris

Reputation: 2286

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.

Upvotes: 1

Related Questions