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

R将大字符串转换为数据帧,r,string,dataframe,R,String,Dataframe,我无法将大文本字符串转换为数据帧。我还没能把这个简单的任务搞清楚。希望得到你的帮助 x <- "1 apple 200 blueberry 3000 pear 4400 raspberry" 试试这个: 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

我无法将大文本字符串转换为数据帧。我还没能把这个简单的任务搞清楚。希望得到你的帮助

x <- "1 apple 200 blueberry 3000 pear 4400 raspberry"
试试这个:

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

r我们可以使用
gsub
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
read.table(text=x,col.names=c('ID','Name'))
#    ID      Name
#1    1     apple
#2  200 blueberry
#3 3000      pear
#4 4400 raspberry

或者,如果没有
gsub
,也可以使用
read.table指定
col.names

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
read.table(text=x,col.names=c('ID','Name'))
#    ID      Name
#1    1     apple
#2  200 blueberry
#3 3000      pear
#4 4400 raspberry

好的,您必须复制一个可复制的示例,但是您尝试的代码丢失了。这将适用于给定的示例字符串,但是Tom O应该知道,如果字符串与该格式不匹配,那么这将失败。@989您能解释r[c(TRUE,FALSE)]的确切功能吗?显然,它只得到数字,但为什么?@JonGrub
r[c(真,假)]
r[c(假,真)]
分别取向量的奇数和偶数索引。它与病媒循环有关。
  read.table(text=x,col.names=c('ID','Name'))
  #     ID      Name
    1    1     apple
    2  200 blueberry
    3 3000      pear
    4 4400 raspberry