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
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 vectormatrix
to turn the vector into the appropriate shapedata.frame
to allow for columns of different modeas.character
and as.numeric
to convert the Count column from a factorHere'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