2010-04-13 78 views
7

我想將csv文件的內容導入到R中,csv文件包含垂直數據的多個部分,用空行和星號分隔。例如如何將包含多個部分的CSV文件導入到R中?

******************************************************** 
* SAMPLE DATA ****************************************** 
******************************************************** 
Name, DOB, Sex 
Rod, 1/1/1970, M 
Jane, 5/7/1980, F 
Freddy, 9.12,1965, M 

******************************************************* 
* Income Data **************************************** 
******************************************************* 
Name, Income 
Rod, 10000 
Jane, 15000 
Freddy, 7500 

我想導入到R作爲兩個單獨的數據框。目前我手動將csv文件剪切成較小的文件,但我認爲我可以使用read.csv和read.csv的skip和nrows設置來完成它,如果我可以計算出secion中斷的位置。

這給了我一個邏輯TRUE爲每個空白行

ifelse(readLines("DATA.csv")=="",TRUE,FALSE) 

我希望有人已經解決了這個問題。

+1

這個SO問題隱約相似http://stackoverflow.com/questions/509595/csv-file-with-multiple-time-series – PaulHurleyuk 2010-04-13 10:20:47

+0

在這種情況下使用'ifelse'是多餘的。 'readLines(「DATA.csv」)==「」'的工作原理是一樣的。 – Marek 2010-04-14 11:44:04

回答

4

在這種情況下,我會做這樣的事情:

# Import raw data: 
data_raw <- readLines("test.txt") 

# find separation line: 
id_sep <- which(data_raw=="") 

# create ranges of both data sets: 
data_1_range <- 4:(id_sep-1) 
data_2_range <- (id_sep+4):length(data_raw) 

# using ranges and row data import it: 
data_1 <- read.csv(textConnection(data_raw[data_1_range])) 
data_2 <- read.csv(textConnection(data_raw[data_2_range])) 

其實你的第一個例子集有不一致的結構,因此data_1看起來很奇怪。

1

也許這個未經測試的片段會有所幫助:

reader <- file("DATA.CSV", "r") 
lines <- readLines(reader) 
writer1 <- textConnection("csv1", open = "w", local = TRUE) 
writer2 <- textConnection("csv2", open = "w", local = TRUE) 
currWriter <- writer1 
lastLine <- length(lines) 
lineNumber <- 4 
repeat { 
    if (lineNumber>lastLine) break 
    if (lines[lineNumber]=="********************************************************") { 
     lineNumber <- lineNumber + 2 # eat two lines 
     currWriter <- writer2 
    } else { 
     writeLines(line, currWriter) 
    } 
    lineNumber <- lineNumber + 1 
} 
close(reader) 
close(writer1) 
close(writer2) 
csv1Reader <- textConnection(csv1, "r") 
csv2Reader <- textConnection(csv2, "r") 
df1 <- read.csv(csv1Reader) 
df2 <- read.csv(csv2Reader) 
close(csv1Reader) 
close(csv2Reader)