R: Reformatting data file -
i have suspect simple data reformatting question. data file (txt) structured observation numbers on separate lines,
1 45 65 78 56 2 89 34 39 55
the desired output is,
1 45 65 1 78 56 2 89 34 2 39 55
suggestions on how make conversion appreciated. thanks.
we read file readlines
. create index variable , split 'lines'. remove first element of list elements, use read.table
read file, , unnest
lines <- readlines('file.txt') library(stringr) #remove leading/lagging spaces if lines <- str_trim(lines) #create index mentioned above based on white space indx <- !grepl('\\s+', lines) #cumsum above index create grouping indx1 <- cumsum(indx) #split lines , change names of list elements lst <- setnames(split(lines, indx1), lines[indx]) #use unnest after reading read.table library(tidyr) unnest(lapply(lst, function(x) read.table(text=x[-1])), gr) # gr v1 v2 #1 1 45 65 #2 1 78 56 #3 2 89 34 #4 2 39 55
or can use map
base r
approach
do.call(rbind,map(cbind, gr=names(lst), lapply(lst, function(x) read.table(text=x[-1]))))
Comments
Post a Comment