Importing one long line of data into R

前端 未结 6 1614
醉酒成梦
醉酒成梦 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:54

    Here's one solution using a variety of tools/hacks, specifically:

    • strplit to split on space characters (\\s)
    • unlist to coerce the list returned by strsplit into a vector
    • matrix to turn the vector into the appropriate shape
    • data.frame to allow for columns of different mode
    • as.character and as.numeric to convert the Count column from a factor

    Here's everything put together:

    txt <- "Cat 14 Dog 15 Horse 16"
    
    out <- data.frame(matrix(unlist(strsplit(txt, "\\s")), ncol = 2, byrow = TRUE, dimnames = list(NULL, c("Animal", "Count"))))
    out$Count <- as.numeric(as.character(out$Count))
    str(out)
    
    'data.frame':   3 obs. of  2 variables:
     $ Animal: Factor w/ 3 levels "Cat","Dog","Horse": 1 2 3
     $ Count : num  14 15 16
    

提交回复
热议问题