How do I skip “#” sign without loop while extract elements?

后端 未结 2 1940
[愿得一人]
[愿得一人] 2021-01-24 05:05

I want to get a new data.frame from this data set,but there are some description with\"#\" between some rows and some rows contain \"#\" sign, I can use \"for\" loop under the c

相关标签:
2条回答
  • 2021-01-24 05:21

    I am assuming you want to read the data from external table(it's unclear from your question), so accordingly i am answering your question,Use comment.char="#" in "read.table" option, it will ignore the lines starting with #.

    See ?read.table.

    So, your first line could be:

    x <- read.table("comm.txt",comment.char="#"),
    

    where "comm.txt" is file which contains data according to your given format.

    You can then use following code to split columns based on delimeter "-"

    library(reshape2)
    LS <- lapply(seq_along(x), function(i){
        colsplit(x[, i], "-", paste0(colnames(x)[i], letters[1:3]))
        }
    )
    
    do.call('cbind', LS)
    

    Hope this helps

    0 讨论(0)
  • 2021-01-24 05:29

    First, remove the rows starting with # from your one-column data frame x:

    vec <- grep("^[^#]", x[[1]], value = TRUE)
    

    Then, create a new data frame based on the remaining data:

    data.frame(V1 = gsub("(.*\\:[0-9]+) .*", "\\1", vec),
               V2 = gsub(".* ([0-9]+) [0-9]+ [0-9]+ *$", "\\1", vec))
    
    #                    V1  V2
    # 1 2013-08-27 16:00:00 200
    # 2 2013-08-27 16:00:01 200
    # 3 2013-08-27 16:00:02 200
    # 4 2013-08-27 16:00:03 200
    
    0 讨论(0)
提交回复
热议问题