Reading text file with multiple space as delimiter in R

妖精的绣舞 提交于 2019-11-28 05:12:59
Simon O'Hanlon

You need to change your delimiter. " " refers to one whitespace character. "" refers to any length whitespace as being the delimiter

 data <- read.table(file, sep = "" , header = F , nrows = 100,
                     na.strings ="", stringsAsFactors= F)

From the manual:

If sep = "" (the default for read.table) the separator is ‘white space’, that is one or more spaces, tabs, newlines or carriage returns.

Also, with a large datafile you may want to consider data.table:::fread to quickly read data straight into a data.table. I was myself using this function this morning. It is still experimental, but I find it works very well indeed.

If you want to use the tidyverse (or readr respectively) package instead, you can use read_table instead.

read_table(file, col_names = TRUE, col_types = NULL,
  locale = default_locale(), na = "NA", skip = 0, n_max = Inf,
  guess_max = min(n_max, 1000), progress = show_progress(), comment = "")

And see here in the description:

read_table() and read_table2() are designed to read the type of textual data where
each column is #' separate by one (or more) columns of space.

If you field have a fixed width, you should consider using read.fwf() which might handle missing values better.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!