R将大字符串转换为数据帧 [英] R convert large character string to dataframe
本文介绍了R将大字符串转换为数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法将大文本字符串转换为数据框。我还无法弄清楚这个简单的任务。希望得到您的帮助。
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
推荐答案
我们可以将 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
或具有 fread
library(data.table)
fread(gsub("(?<=[a-z])\\s+", "\n", x, perl=TRUE), col.names = c("id", "name"))
或者在没有 gsub $的情况下也可以使用c $ c>通过使用
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
这篇关于R将大字符串转换为数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文