【问题标题】:how can i read a csv file containing some additional text data我如何读取包含一些附加文本数据的 csv 文件
【发布时间】:2013-03-02 09:37:00
【问题描述】:

我需要在 R 中读取一个 csv 文件。但该文件在某些​​行中包含一些文本信息,而不是逗号值。所以我无法使用 read.csv(fileName) 方法读取该文件。 文件内容如下:

name:russel date:21-2-1991
abc,2,saa
anan,3,ds
ama,ds,az
,,

name:rus date:23-3-1998
snans,32,asa
asa,2,saz

我只需要将每个名称、日期对的值存储为数据框。为此,我如何读取该文件?

其实我需要的输出是

>dataFrame1
    abc,2,saa
    anan,3,ds
    ama,ds,az
>dataFrame2
    snans,32,asa
    asa,2,saz

【问题讨论】:

标签: r csv


【解决方案1】:

您可以使用scan 读取数据,并使用grepsub 函数提取重要值。

正文:

text <- "name:russel date:21-2-1991
abc,2,saa
anan,3,ds
ama,ds,az
,,

name:rus date:23-3-1998
snans,32,asa
asa,2,saz"

这些命令会生成一个包含名称和日期值的数据框。

# read the text
lines <- scan(text = text, what = character())
# find strings staring with 'name' or 'date'
nameDate <- grep("^name|^date", lines, value = TRUE)
# extract the values
values <- sub("^name:|^date:", "", nameDate)
# create a data frame
dat <- as.data.frame(matrix(values, ncol = 2, byrow = TRUE,
                            dimnames = list(NULL, c("name", "date"))))

结果:

> dat
    name      date
1 russel 21-2-1991
2    rus 23-3-1998

更新

要从不包含名称和日期信息的字符串中提取值,可以使用以下命令:

# read data
lines <- readLines(textConnection(text))
# split lines
splitted <- strsplit(lines, ",")
# find positions of 'name' lines
idx <- grep("^name", lines)[-1]
# create grouping variable
grp <- cut(seq_along(lines), c(0, idx, length(lines)))
# extract values
values <- tapply(splitted, grp, FUN = function(x)
                                        lapply(x, function(y)
                                                    if (length(y) == 3) y))
create a list of data frames
dat <- lapply(values, function(x) as.data.frame(matrix(unlist(x),
                                                       ncol = 3, byrow = TRUE)))

结果:

> dat
$`(0,7]`
    V1 V2  V3
1  abc  2 saa
2 anan  3  ds
3  ama ds  az

$`(7,9]`
     V1 V2  V3
1 snans 32 asa
2   asa  2 saz

【讨论】:

  • 先生。这个答案对我非常有用。但我需要的实际输出不同。请参阅问题中的编辑。
【解决方案2】:

我会首先将整个文件作为字符列表读取,即文件中每一行的字符串,这可以使用readLines 来完成。接下来,您必须找到新日期的数据开始的位置,即查找,,,请参阅grep。然后取每个数据块的第一个条目,例如使用 stringr 包中的 str_extract。最后,您需要拆分所有剩余的数据字符串,请参阅strsplit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2016-08-26
    • 1970-01-01
    • 2018-03-04
    相关资源
    最近更新 更多