如何从R中的csv文件中提取不同类型的数据

How to extract different type of data from a csv file in R

我有一个 csv 文件 (dropbox link),其中包含由 blank/empty 行分隔的两种类型的信息:

第二个table的header由3个独立的lines/rows组成。理想情况下,我只想保留一个,以 ID.

开头

我想将以上内容以 list 格式导入 R

> print(data)

$experiment name
[1] "test1"

$date
[1] "01/01/2015"

$protocol
[1] "test2"

$name
[1] "John Doe"

$data
   ID name value
1  A1   AA   0.1
2  A2   BB  0.16
3  A3   CC  0.12
4  A4   DD  0.45
5  A5   EE  0.35
6  B1   FF   1.2
7  B2   GG  1.12
8  B3   HH  1.05
9  B4   II  1.21
10 B5   JJ  1.18

我已尝试 scan csv 文件并有条件地导入行,但无济于事。是否有一个基本函数或一组函数允许我导入用空行分隔的两个 table,并有条件地 read-in 来自 [=25= 的第二个 table ]ID字符起?

非常感谢您的帮助!

你可以做这样的事情(不完全是你想要的,但这是一个好的开始):

## use readlines since you unstrctred data
ll <- readLines("data.csv")     
list(
     ## I assume that the data is always in 3 first lines
     ## remove extra comma then use read.table   
     settings = read.table(text=gsub(',','',ll[seq(3)]),sep=':'),
     ## find where the data begin using grep
     data= read.table(text=ll[-seq(grep("ID",ll)-1)],header=TRUE,sep=','))

# $settings
#                V1         V2
# 1 experiment name      test1
# 2            date 01/01/2015
# 3        protocol      test2
# 
# $data
#    ID name value
# 1  A1   AA  0.10
# 2  A2   BB  0.16
# 3  A3   CC  0.12
# 4  A4   DD  0.45
# 5  A5   EE  0.35
# 6  B1   FF  1.20
# 7  B2   GG  1.12
# 8  B3   HH  1.05
# 9  B4   II  1.21
# 10 B5   JJ  1.18

起点是:

data <- list()
all <- read.csv("data.csv", header=F, stringsAsFactors=F)
blank.line <- which(all[[1]]=="")
for (i in 1:(blank.line-1)) data[[all$V1[i]]] <- all$V2[i]
data$data <- read.csv("data.csv", skip=grep("^ID",all[,1])-1, header=T, stringsAsFactors=F)

数据中列表元素的名称与您所写的不完全相同 - 如果重要,可以通过 gsub() 去掉冒号来解决这些问题。

根据关于顶部 table 具有可变长度

的评论编辑的代码