3

在 R 中,我正在使用 csv 读取带有注释的文件

read.data.raw = read.csv(inputfile, sep='\t', header=F, comment.char='')

该文件如下所示:

#comment line 1
data 1<tab>x<tab>y
#comment line 2
data 2<tab>x<tab>y
data 3<tab>x<tab>y

现在我使用提取未注释的行

comment_ind = grep( '^#.*', read.data.raw[[1]])
read.data = read.data.raw[-comment_ind,]

这让我:

 data 1<tab>x<tab>y
 data 2<tab>x<tab>y
 data 3<tab>x<tab>y

我正在通过一些单独的脚本修改这些数据,该脚本维护行数/列数,并希望将其放回原始读取数据(带有用户评论)并像这样将其返回给用户

#comment line 1
modified data 1<tab>x<tab>y
#comment line 2
modified data 2<tab>x<tab>y
modified data 3<tab>x<tab>y

由于我在 read.data 中提取的数据保留了行名 row.names(read.data),所以我尝试了

original.read.data[as.numeric(row.names(read.data)),] = read.data

但这不起作用,我得到了一堆 NA/s

有任何想法吗?

4

1 回答 1

1

这是做你想做的吗?

read.data.raw <- structure(list(V1 = structure(c(1L, 3L, 2L, 4L, 5L),
   .Label = c("#comment line 1", "#comment line 2", "data 1", "data 2", 
   "data 3"), class = "factor"), V2 = structure(c(1L, 2L, 1L, 2L, 2L), 
   .Label = c("", "x"), class = "factor"), V3 = structure(c(1L, 2L, 1L,
   2L, 2L), .Label = c("", "y"), class = "factor")), .Names = c("V1", 
   "V2", "V3"), class = "data.frame", row.names = c(NA, -5L))

comment_ind = grep( '^#.*', read.data.raw[[1]])
read.data <- read.data.raw[-comment_ind,]
# modify V1
read.data$V1 <- gsub("data", "DATA", read.data$V1)
# rbind() and then order() comments into original places
new.data <- rbind(read.data.raw[comment_ind,], read.data)
new.data <- new.data[order(as.numeric(rownames(new.data))),]
于 2012-08-27T21:41:06.260 回答