How to use contents of an array to mount the name of a file to be saved?

Asked

Viewed 83 times

7

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

My data is something like that (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 don’t know how I can get it. I tried (it didn’t work):

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

Someone knows a solution?

1 answer

7


Just you replace the nomes[i]".txt" for paste0(nomes[i],".txt"). The loop will stay 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 function paste is used to concatenate strings and by default uses a space to join them. When I use paste0 it concatenates without spaces.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.