Reverse multiple columns in multiple tab separated files

Hello. I'm new to R and am facing a problem. I have hundreds of tab separated files and their format are as follow:

Column 1 Column 2 Column 3

I'd like to change the position of columns 2 and 3:

Column 1 Column 3 Column 2.

BUT, the columns don't have names.So far I managed to load the files:

#> Load files

arquivos_txt = dir_ls('tempor')
lista_df = map(arquivos_txt, read.delim)

And since the columns don't have names, I'm trying to use the lapply function to change their orders, but I always end up with a warning:

#> Apply function, but columns do'nt have any name or number. I tried numbers:

lista_df2 = lapply(lista_df, FUN = function(x){x[c('1,3,2')]})

Error in [.data.frame(x, c("1,3,2")) : indefinite columns selected.

I have attatched a snippet of a tab separated file.

Please, what can I do to reverse these two columns? Thanks in advance.

Instead of listing the columns in a string, try listing the column numbers.

lista_df2 = lapply(lista_df, FUN = function(x){x[c(1, 3, 2)]})

Hi, @scottyd22 , thank you very much for your tip! It has worked! In order to save these documents I need to use the write.table function? I have used:

#>  Save each document with reversed columns

write.table(lista_df2, sep = “ ”)

but it's not working. Should I add something to this function?

One approach would be to create a function to step through that writes each file to your desired location. In the example below (which only has 2 tables), the write_files() function will take each newly created table, generate a "filepath" name, write the table to the desired location with the new name, and then return a success message. The message is not necessary, but nice to see after executing the lapply.

# function to write each table, based on index 'i'
write_files = function(i) {
  # name each table "table_i.txt"
  filepath = paste0('your_desired_location/table_', i, '.txt')

  write.table(x = lista_df2[[i]], # the i-th table in lista_df2
              file = filepath,
              sep = ' ')

  # output message
  message = paste0('table_', i, ' success!')

# step through all indexes (1 to length of list)
outcome = lapply(1:length(lista_df2), write_files)

#> [[1]]
#> [1] "table_1 success!"
#> [[2]]
#> [1] "table_2 success!"

Created on 2022-09-21 with reprex v2.0.2.9000

Wow, I'd never thought of it! I'm going to study R from now on, so I need toget used to this. Again, thank you very much!!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.