How to split a character vector into data frame?

前端 未结 4 2136
南旧
南旧 2020-12-15 12:47

I\'m still relatively new to R and hope you can again help me. I have a character vector with a length of 42000. The vector looks like this:

a <- c(\"blab         


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-15 13:03

    You can almost use read.table directly, but your date format isn't the same as what R would use for the colClasses argument.

    No problem. Just specify your own class and proceed :-)

    ## Create a class called "ymdDate"
    setClass("ymdDate")
    setAs("character", "ymdDate", function(from) as.Date(from, format="%Y%m%d"))
    
    ## Use `read.table` on your character vector. For convenience, I've
    ##   used `gsub` to get rid of the `.tsv` in before reading it in.
    out <- read.table(text = gsub(".tsv$", "", a), header = FALSE, 
                      sep = "-", colClasses=c("character", "ymdDate", "integer"))
    out
    #          V1         V2 V3
    # 1 blablabla 1996-01-01  1
    # 2 blablabla 1996-01-01  2
    # 3 blablabla 1996-01-01  3
    str(out)
    # 'data.frame':  3 obs. of  3 variables:
    #  $ V1: chr  "blablabla" "blablabla" "blablabla"
    #  $ V2: Date, format: "1996-01-01" "1996-01-01" "1996-01-01"
    #  $ V3: int  1 2 3
    

提交回复
热议问题