簡體   English   中英

在 R 中讀取具有不同列長和空格的數據

[英]Reading in data with different column lengths and spaces in R

我有看起來像這樣的數據:

category 2011 2012 2013 2104
word word word 15,000.11 1,000.15 13,001.50 20,000,001.52
word 2,000.120 400,000.00 57,000.523 402,000,111
word word 4,000.120 455,000.02 57,600.87 403,000,111.18
word 2,056.120 678,000.00 670,000.523 402,009,111.65

它位於 .csv 文件中。 我想讀進去,所以它分成幾列,但它們的長度都不同,所以我不確定如何。 我知道我可以用空格分隔,但第一列中的一些單詞之間有空格。

category         2011      2012         2013         2104
word word word  15,000.11  1,000.15    13,001.50    20,000,001.52
word            2,000.120  400,000.00  57,000.523   402,000,111
word word       4,000.120  455,000.02  57,600.87    403,000,111.18
word            2,056.120  678,000.00  670,000.523  402,009,111.65

如果我沒有正確提出這個問題,我深表歉意。 謝謝你的幫助!

我們可以在用readLines讀取數據集后用sub做分隔符

lines[-1] <- sub("^([A-Za-z ]+)(?=\\s[0-9])", "'\\1'", lines[-1], perl = TRUE)
read.table(textConnection(lines), header = TRUE, check.names = FALSE)
#      category      2011       2012        2013           2104
#1 word word word 15,000.11   1,000.15   13,001.50  20,000,001.52
#2           word 2,000.120 400,000.00  57,000.523    402,000,111
#3      word word 4,000.120 455,000.02   57,600.87 403,000,111.18
#4           word 2,056.120 678,000.00 670,000.523 402,009,111.65

數據

lines <- readLines('file.csv')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM