-1

I want to load a text file that looks like the following into R, remove all spaces, then rewrite the file.

1 061
061 1
0 081
080 1
0 061
060 1
1 051
051 1
0 101
100 1

The way I'd go about this is with readlines(), removing the spaces in each row, then rewriting.

Is that the best way?

This question is different from just asking how to remove spaces from a string as it involves data framed as rows in a predictable pattern.

Union find
  • 7,759
  • 13
  • 60
  • 111

1 Answers1

1

I'm not sure exactly what you mean by removing the spaces, but if the data is in the format you describe, then read.table can easily read it.

> tbl <- read.table(text = "
    1 061
    061 1
    0 081
    080 1
    0 061
    060 1
    1 051
    051 1
    0 101
    100 1
")
> tbl
    V1  V2
1    1  61
2   61   1
3    0  81
4   80   1
5    0  61
6   60   1
7    1  51
8   51   1
9    0 101
10 100   1

If you then want to merge the columns so you get the strings without spaces, you simply do this

> no_space <- apply(tbl, 1, function(row) paste0(row, collapse = ""))
> no_space
 [1] "161"  "611"  "081"  "801"  "061"  "601"  "151"  "511" 
 [9] "0101" "1001"

If you want that better formated, cat can do it for you.

> cat(paste0(no_space, collapse = "\n"))
161
611
081
801
061
601
151
511
0101
1001

You can write this to a file using the file argument to cat.

Thomas Mailund
  • 1,674
  • 10
  • 16