Skip to content

Instantly share code, notes, and snippets.

@AbdouSeck
Created October 3, 2018 00:09
Show Gist options
  • Save AbdouSeck/e1b50c14bc0ebe6a849675254c07bc06 to your computer and use it in GitHub Desktop.
Save AbdouSeck/e1b50c14bc0ebe6a849675254c07bc06 to your computer and use it in GitHub Desktop.
R code to answer stackoverflow question https://stackoverflow.com/q/52610894/3135417
# persons.txt
# Person 1
# Class Grade
# Math A
# Science C
# English A
# Person 2
# Class Grade
# Math D
# English A
manipulate_file_data <- function(filename) {
person_text <- readChar(filename, file.info(filename)$size)
persons <- strsplit(person_text, split = '\\n(?=Person\\s\\d)', perl = T)
do.call(rbind, lapply(persons, function(chr) {
chr <- unlist(strsplit(chr, split = '(?<=Person\\s\\d)\\n', perl = T))
chr[2] <- gsub('\\s{2,}', ',', chr[2])
df <- read.csv(textConnection(chr[2]), header = T)
cbind(data.frame(Name=chr[1]), df)
}))
}
manipulate_file_data('persons.txt')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment