将文本读入 data.frame,其中字符串值包含空格
Reading text into data.frame where string values contain spaces
当字符串值包含干扰 read.table
的空格时,将文本从打印的 data.frame 读入 data.frame 的最简单方法是什么?例如,这个 data.frame 摘录不会造成问题:
candname party elecVotes
1 BarackObama D 365
2 JohnMcCain R 173
我可以毫无问题地将其粘贴到 read.table
调用中:
dat <- read.table(text = " candname party elecVotes
1 BarackObama D 365
2 JohnMcCain R 173", header = TRUE)
但是如果数据中有像这样带有空格的字符串:
candname party elecVotes
1 Barack Obama D 365
2 John McCain R 173
然后 read.table
抛出错误,因为它将 "Barack" 和 "Obama" 解释为两个单独的变量。
将文件读入 L
,删除行号并使用 sub
和指定的正则表达式在剩余字段之间插入逗号。 (注意 "\d"
匹配任何数字,"\S"
匹配任何非空白字符。)现在使用 read.csv
:
重新阅读它
Lines <- " candname party elecVotes
1 Barack Obama D 365
2 John McCain R 173"
# L <- readLines("myfile") # read file; for demonstration use next line instead
L <- readLines(textConnection(Lines))
L2 <- sub("^ *\d+ *", "", L) # remove row numbers
read.csv(text = sub("^ *(.*\S) +(\S+) +(\S+)$", "\1,\2,\3", L2), as.is = TRUE)
给予:
candname party elecVotes
1 Barack Obama D 365
2 John McCain R 173
这是正则表达式的可视化:
^ *(.*\S) +(\S+) +(\S+)$
当字符串值包含干扰 read.table
的空格时,将文本从打印的 data.frame 读入 data.frame 的最简单方法是什么?例如,这个 data.frame 摘录不会造成问题:
candname party elecVotes
1 BarackObama D 365
2 JohnMcCain R 173
我可以毫无问题地将其粘贴到 read.table
调用中:
dat <- read.table(text = " candname party elecVotes
1 BarackObama D 365
2 JohnMcCain R 173", header = TRUE)
但是如果数据中有像这样带有空格的字符串:
candname party elecVotes
1 Barack Obama D 365
2 John McCain R 173
然后 read.table
抛出错误,因为它将 "Barack" 和 "Obama" 解释为两个单独的变量。
将文件读入 L
,删除行号并使用 sub
和指定的正则表达式在剩余字段之间插入逗号。 (注意 "\d"
匹配任何数字,"\S"
匹配任何非空白字符。)现在使用 read.csv
:
Lines <- " candname party elecVotes
1 Barack Obama D 365
2 John McCain R 173"
# L <- readLines("myfile") # read file; for demonstration use next line instead
L <- readLines(textConnection(Lines))
L2 <- sub("^ *\d+ *", "", L) # remove row numbers
read.csv(text = sub("^ *(.*\S) +(\S+) +(\S+)$", "\1,\2,\3", L2), as.is = TRUE)
给予:
candname party elecVotes
1 Barack Obama D 365
2 John McCain R 173
这是正则表达式的可视化:
^ *(.*\S) +(\S+) +(\S+)$