How to use contents of a vector to assemble the name of a file to be saved?

7

I have tried to use colnames() , names() and nothing works.

My data is something like (however, I have 38,000 names and 38,000 columns):

nomes <- c("nome105", "outro.nome_26", "qualquerCoisa")
dados <- as.data.frame(matrix(c(25,37,48,6,32,9,10,111,140,60,72,91), ncol=3))

What I need is the .txt files:

write.table(dados[,1], "nome105.txt", sep = "\t", row.names = F, col.names = F)
write.table(dados[,2], "outro.nome_26.txt", sep = "\t", row.names = F, col.names = F)
write.table(dados[,3], "qualquerCoisa.txt", sep = "\t", row.names = F, col.names = F)

In the meantime, I would like to find a way to optimize the service, but I do not know how I can get it. I tried (did not work):

for(i in 1:ncol(dados)){
   write.table(dados[,i], nomes[i]".txt", sep = "\t", 
               row.names = F, col.names = F)
}

Does anyone know a solution?

    
asked by anonymous 10.05.2016 / 21:19

1 answer

6

Simply replace nomes[i]".txt" with paste0(nomes[i],".txt") . The loop will look like this:

for(i in 1:ncol(dados)){
  write.table(dados[,i], paste0(nomes[i],".txt"), sep = "\t", 
              row.names = F, col.names = F)
}

The paste function is used to concatenate strings and by default uses a space to join them. When I use paste0 it concatenates without spaces.

    
10.05.2016 / 21:31