简体   繁体   English

替换R中的行

[英]Replacing rows in R

In R am reading a file with comments as csv using 在R am中读取带有注释为csv的文件

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

The file looks like this: 该文件如下所示:

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

Now I extract the uncommented lines using 现在我使用提取未注释的行

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

Which leaves me: 哪个让我:

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

I am modifying this data through some separate script which maintains the number of rows/cols and would like to put it back into the original read data (with the user comments) and return it to the user like this 我正在通过一些单独的脚本修改这些数据,该脚本维护行/列的数量,并希望将其放回原始读取数据(带有用户注释)并将其返回给用户,如下所示

#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

Since the data I extracted in read.data preserves the row names row.names(read.data), I tried 由于我在read.data中提取的数据保留了行名称row.names(read.data),我试过了

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

But that didn't work, and I got a bunch of NA/s 但这没用,我得到了一堆NA / s

Any ideas? 有任何想法吗?

Does this do what you want? 这样做你想要的吗?

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))),]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM