Importing one long line of data into R

前端 未结 6 1615
醉酒成梦
醉酒成梦 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条回答
  •  梦毁少年i
    2021-02-05 19:46

    Assuming that the white space is a delimiter, you can use the following mechanism:

    • Use scan to read the file
    • Convert the results to a matrix, then to a data.frame

    The code:

    x <- scan(file=textConnection("
    Cat 14 Dog 15 Horse 16
    "), what="character")
    
    xx <- as.data.frame(matrix(x, ncol=2, byrow=TRUE))
    names(xx) <- c("Animal", "Number")
    xx$Number <- as.numeric(xx$Number)
    

    The results:

    xx
    
      Animal Number
    1    Cat      1
    2    Dog      2
    3  Horse      3
    

提交回复
热议问题