[R] how to separate stuck row elements?

Berend Hasselman bhh at xs4all.nl
Fri Nov 30 16:19:25 CET 2012


On 30-11-2012, at 13:55, Jaime Otero Villar wrote:

> Hi,
> 
> I was wondering if it's possible to separate elements in multiple rows that actually should appear in different columns. I have a file where in certain lines there are elements not separated, and they certainly should appear in different columns (an example of the file is attached). The point is that I do not want to manually add a space in the txt file, however, I did not manage to do it automatically in R...
> 

Taking into account your description simulate file.
Use readLines to read the file into a vector of lines.
Use gsub() to replace each - with a single space.
Finally use read.table to get a dataframe.


# use the example consisting of 3 lines
data.text <- "-100 -100-3456-3456-3456-100 -100
23 -3456-3456-189 34 56 78
-100 34 56 21 44 65 78"

x.lines <- readLines(textConnection(data.text))
x.lines

# replace - with single space 
 
x.1 <- gsub("-"," ",x.lines)
x.1

read.table(text=x.1, header=FALSE) 

Berend




More information about the R-help mailing list