Splitting a string by more than one space

Viewed 2261

I am trying to load some data into R that is in the following format (as a text file)

Name                  Country            Age
John,Smith            United Kingdom     20
Washington,George     USA                50
Martin,Joseph         Argentina          43

The problem I have is that the "columns" are separated by spaces such that they all line up nicely, but one row may have 5 spaces between values and the next 10 spaces. So when I load it in using read.delim I get a one column data.frame with

"John,Smith            United Kingdom     20"

as the first observation and so on.

Is there any way I can either:

  1. Load the data into R into a usable format? or
  2. Split the character strings up into separate columns once I load it in in the one column format?

My thought was to split the character strings by spaces, except it would need to be between 2 and x spaces (so, for example, "United Kingdom" stays together and doesn't become "United" "" "Kingdom"). But I don't know if that is possible.

I tried strsplit(data.frame[,1], sep="\\s") but it returns a list of character strings like:

"John,Smith" "" "" "" "" "" "" "" "United" "" "Kingdom" "" ""...

which I don't know what to do with.

2 Answers
Related