0
$\begingroup$

How can I generate a code for switching rows and columns of a random .txt file? The data inside that file may contain strings, which must be switched too.

I import the data in a table format, but I want to export the same file with just rows and columns interchanged.

A quick way of doing it?

The data can be for example:

enter image description here Thank you in advance

$\endgroup$
  • $\begingroup$ Can you provide a sample txt file so that we can work with it? $\endgroup$ – Fraccalo Jul 4 '18 at 12:14
  • 1
    $\begingroup$ Are you looking for Transpose ? $\endgroup$ – mmeent Jul 4 '18 at 12:17
  • $\begingroup$ I tried with transpose, but when I'm exporting the file, it doesn't look like the input file $\endgroup$ – Guillermo Martínez Somonte Jul 4 '18 at 12:20
  • $\begingroup$ Based on your example, have you tried exporting with "TSV" as the format (third argument of export)? $\endgroup$ – mmeent Jul 4 '18 at 12:23
3
$\begingroup$

See below an example where I swap second and third row and I all the columns:

data = {{"a", "b", "c"}, {1, 2, 3}, {4, 5, 6}};

(* Rearrange rows *)
data[[{1, 2, 3}]] = data[[{1, 3, 2}]];

(* Rearrange columns *)    
data[[;; , {1, 2, 3}]] = data[[;; , {3, 1, 2}]]

{{"c", "a", "b"}, {6, 4, 5}, {3, 1, 2}}

(* Export in txt file *)
Export["test.txt", data, "Table"]

Next time please provide a .txt file to work with, not just an image of it.

$\endgroup$
  • $\begingroup$ Sorry, I tried but I couldn't find the option for uploading the file (except the image! $\endgroup$ – Guillermo Martínez Somonte Jul 4 '18 at 12:52
  • 1
    $\begingroup$ @Guillermo There is no direct way to upload a file here, but you can create e.g. a pastebin and provide a link to it. $\endgroup$ – MarcoB Jul 4 '18 at 13:02
  • $\begingroup$ Alright, for future posts, thank you! $\endgroup$ – Guillermo Martínez Somonte Jul 5 '18 at 13:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.