[英]R convert large character string to dataframe
我在將大型文本字符串轉換為數據幀時遇到問題。 我一直無法解決這個簡單的任務。 希望得到你的幫助。
x <- "1 apple 200 blueberry 3000 pear 4400 raspberry"
我想將其轉換為如下所示的數據框:
id name
1 apple
200 blueberry
30000 pear
4400 raspberrry
我們可以使用帶有read.table
gsub
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"))
或者通過使用read.table
指定col.names
,這也可以在沒有gsub
的情況下工作
read.table(text=x,col.names=c('ID','Name'))
# ID Name
#1 1 apple
#2 200 blueberry
#3 3000 pear
#4 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
read.table(text=x,col.names=c('ID','Name'))
# ID Name
1 1 apple
2 200 blueberry
3 3000 pear
4 4400 raspberry
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.