how to divide an input file into different output files based on information of the first column at input in R? -
i want make saparated output files based on unique values in input file. input looks like:
input.txt: 1 23 1 22 1 2 1 45 1 33 2 22 2 1 2 1 3 22 3 45 3 44 i want have separated output files base on uniq values in first column of input. so:
out1.txt:
1 23 1 22 1 2 1 45 1 33 out2.txt
2 22 2 1 2 1 out3.txt
3 22 3 45 3 44 any suggestion? real input huge file
since tagged r, provide r answer. here base r method first, data.table method down below.
## read data r df <- read.table("input.txt") ## split data frame first column s <- split(df, df[[1l]]) ## write each table in 's' file 'out*.txt' invisible( map(write.table, x = s, file = sprintf("out%s.txt", seq_along(s))) ) now should have 3 new files "out1.txt", "out2.txt", , "out3.txt" based on example data.
alternatively, can speed data.table package.
library(data.table) ## read data dt <- fread("input.txt") ## write each chunk of 'dt' file 'out*.txt' group dt[, write.table(cbind(v1 = .grp, .sd), sprintf("out%s.txt", .by)), = v1] obviously makes assumptions column names, easy change values accordingly.
Comments
Post a Comment