Tom O
Tom O

Reputation: 1597

R convert large character string to dataframe

I am having trouble converting a large text string to a dataframe. I've been unable to figure this simple task out yet. Hoping for your help.

x <- "1 apple 200 blueberry 3000 pear 4400 raspberry"

I'd like to convert this to a dataframe that looks like this:

id    name
1     apple
200   blueberry
30000 pear
4400  raspberrry

Upvotes: 17

Views: 27829

Answers (3)

akrun
akrun

Reputation: 887691

We can use gsub with read.table

read.table(text=gsub("(?<=[a-z])\\s+", "\n", x, perl=TRUE), 
            header=FALSE, col.names = c("id", "name"))
#    id      name
#1    1     apple
#2  200 blueberry
#3 3000      pear
#4 4400 raspberry

Or with fread

library(data.table)
fread(gsub("(?<=[a-z])\\s+", "\n", x, perl=TRUE), col.names = c("id", "name"))

Or this would also work without the gsub by specifying the col.names with read.table

read.table(text=x,col.names=c('ID','Name'))
#    ID      Name
#1    1     apple
#2  200 blueberry
#3 3000      pear
#4 4400 raspberry

Upvotes: 21

Shenglin Chen
Shenglin Chen

Reputation: 4554

  read.table(text=x,col.names=c('ID','Name'))
  #     ID      Name
    1    1     apple
    2  200 blueberry
    3 3000      pear
    4 4400 raspberry

Upvotes: 6

989
989

Reputation: 12935

Try this:

r <- unlist(strsplit(x, " "))
data.frame(id=as.numeric(r[c(TRUE,FALSE)]), name=r[c(FALSE,TRUE)])

#    id      name
#1    1     apple
#2  200 blueberry
#3 3000      pear
#4 4400 raspberry

Upvotes: 8

Related Questions