R将大字符串转换为数据帧

Tom*_*m O 7 string r dataframe

我在将大型文本字符串转换为数据帧时遇到问题.我一直无法解决这个简单的任务.希望得到你的帮助.

x <- "1 apple 200 blueberry 3000 pear 4400 raspberry"
Run Code Online (Sandbox Code Playgroud)

我想将其转换为如下所示的数据框:

id    name
1     apple
200   blueberry
30000 pear
4400  raspberrry
Run Code Online (Sandbox Code Playgroud)

akr*_*run 6

我们可以使用gsubread.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
Run Code Online (Sandbox Code Playgroud)

或者 fread

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

或者这也可以在没有gsub指定col.nameswith的情况下工作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
Run Code Online (Sandbox Code Playgroud)


She*_*hen 6

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


989*_*989 5

试试这个:

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
Run Code Online (Sandbox Code Playgroud)