我想将csv文件的内容导入R,csv文件垂直包含多个数据部分,用空行和星号分隔。例如
********************************************************
* 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中断的地方。
这为每个空行
提供了逻辑TRUEifelse(readLines("DATA.csv")=="",TRUE,FALSE)
我希望有人已经解决了这个问题。
答案 0 :(得分: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 :(得分: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)