parse2data.frame <- function(x) { ## Purpose: Parse a string to generate a data frame. ## Arguments: ## x: a string with header and multiple rows of text that resembles a data frame. ## Fields are separated by comma. ## Return: a data frame ## Author: Feiming Chen, Date: 19 Jun 2017, 10:12 ## ________________________________________________ d <- read.csv(textConnection(x), as.is = T) i <- sapply(d, is.character) d[i] <- lapply(d[i], trimws) d } if (F) { # Unit Test a = " Test, ID, Name t1 , 3, Sun t2 , 5, Moon t3, 2, Earth " b <- parse2data.frame(a) str(b) ## 'data.frame': 3 obs. of 2 variables: ## $ ID : int 3 5 2 ## $ Name: Factor w/ 3 levels " Earth"," Moon",..: 3 2 1 }
Monday, June 19, 2017
Parse a string to generate a data frame
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment