ben_aaron ben_aaron - 3 months ago 5
R Question

Write column values to file with matching value from second column in R

I have a dataframe

df
in R that has several columns, of which
columnA
and
columnB
are of interest here:

columnA columnB
ab1 'This is a string'
ts4 'This is another string'
pq9 'This is yet another string'


I want to write the strings to a file and include the matching
columnA
value in the filename.

sapply(df$columnB, function(x){
write.table(x,
file = paste("matching_column_a_",
which(x == df$columnB, arr.ind = T),
".txt",
sep = ""),
col.names = FALSE,
row.names = FALSE,
append=F,
sep = "\t",
quote = FALSE)
})


However, my try gives only an index of the rows but that is not of use for me.

Is there a way to write it to a file where the matching filename of the file with the
columnB
string is something like
matching_column_a_ab1.txt
,
...a_ts4.txt
, etc?

Answer

We can loop through the sequence of rows, use that index to subset the column values for writing it to different files.

lapply(seq_len(nrow(df1)), function(i)
       write.table(df1$columnB,
                  file = paste0("matching_column_a_", df1$columnA[i], ".txt"),
                  col.names = FALSE,
                  row.names = FALSE,
                  append=FALSE,
                  sep = "\t",
                  quote = FALSE) )