Importing one long line of data into R

前端 未结 6 1621
醉酒成梦
醉酒成梦 2021-02-05 18:58

I have a large data file consisting of a single line of text. The format resembles

Cat    14  Dog    15  Horse  16

I\'d eventually like to get

6条回答
  •  爱一瞬间的悲伤
    2021-02-05 19:33

    Method 1: (extracting from long vector with seq()

    > inp <- scan(textConnection("Cat 14 Dog 15 Horse 16"), what="character")
    Read 6 items
    > data.frame(animal = inp[seq(1,length(inp), by=2)], 
                 numbers =as.numeric(inp[seq(2,length(inp), by=2)]))
      animal numbers
    1    Cat      14
    2    Dog      15
    3  Horse      16
    

    Method 2: (using the "what" argument to scan to greater effect)

    > inp <- data.frame(scan(textConnection("Cat 14 Dog 15 Horse 16"), 
                         what=list("character", "numeric")))
    Read 3 records
    > names(inp) <- c("animals", "numbers")
    > inp
      animals numbers
    1     Cat      14
    2     Dog      15
    3   Horse      16
    

    This is a refinement of the Method 2: (was worried about possibility of very long column names in the result from scan() so I read the help page again and added names to the what argument values:

    inp <- data.frame(scan(textConnection("Cat 14 Dog 15 Horse 16"), 
                            what=list( animals="character", 
                                       numbers="numeric")))
    Read 3 records
    > inp
      animals numbers
    1     Cat      14
    2     Dog      15
    3   Horse      16
    

提交回复
热议问题