将文本读入data.frame,其中字符串值包含空格

Sam*_*rke 4 r read.table

当存在包含空间干扰的字符串值时,从打印的data.frame读取文本到data.frame的最简单方法是read.table什么?例如,此data.frame摘录不会造成问题:

     candname party elecVotes
1 BarackObama     D       365
2  JohnMcCain     R       173
Run Code Online (Sandbox Code Playgroud)

我可以将它粘贴到一个read.table没有问题的电话中:

dat <- read.table(text = "     candname party elecVotes
1 BarackObama     D       365
2  JohnMcCain     R       173", header = TRUE)
Run Code Online (Sandbox Code Playgroud)

但是如果数据包含带有这样的空格的字符串:

      candname party elecVotes
1 Barack Obama     D       365
2  John McCain     R       173
Run Code Online (Sandbox Code Playgroud)

然后read.table抛出一个错误,因为它将"Barack"和"Obama"解释为两个独立的变量.

G. *_*eck 7

读入文件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)
Run Code Online (Sandbox Code Playgroud)

赠送:

      candname party elecVotes
1 Barack Obama     D       365
2  John McCain     R       173
Run Code Online (Sandbox Code Playgroud)

这是正则表达式的可视化:

^ *(.*\S) +(\S+) +(\S+)$
Run Code Online (Sandbox Code Playgroud)

正则表达式可视化

Debuggex演示