tmp <- split(Z[, 3:4], Z[,2]) fn <- file('final.txt', 'wt') for (i in 1:length(tmp)){ writeLines(names(tmp)[i], fn) lapply(tmp[[i]], function(x) writeLines(paste(x, collapse='\t'), fn)) } close(fn)