0
$\begingroup$

Suppose I have a text file, in this format:

1 1 1 1 1 99.5016 10.43 99.5016 99.5016 7.074 47.8012 10.43 7.074 7.074
2 1 1 1 1 99.5016 10.43 99.5016 99.5016 7.074 47.8012 10.43 7.074 7.074
3 1 1 1 1 99.5016 10.43 99.5016 99.5016 7.074 47.8012 10.43 7.074 7.074

And I want to add up all the elements in the ones column, for a certain number of lines. How would I do that?

I have this currently:

data = Import[
  "/Users/myname/Documents/foldername/filename.txt", "Table"]
Total@data[[All, 2]];
$\endgroup$
0

2 Answers 2

1
$\begingroup$

You need Import, Part (i.e. [[...]]), probably Span (i.e. ;;), and Total.

Import the data:

data = Import["path\to\yourdatafile.txt", "Table"];

Sum all entries in the first column:

Total@data[[All, 1]]

Sum entries in the third column and in the second to third row:

Total@data[[2 ;; 3, 3]]

Sum entries in column 2, rows 1 and 3:

Total@data[[{1, 3}, 2]]
$\endgroup$
9
  • $\begingroup$ I believe I did everything you mentioned, but it doesn't produce an output. data=Import["textfile", "Table"]; Total@data[[2;;10000,2]]; (If I wanted to add up everything in the second column) $\endgroup$ Commented May 11, 2016 at 19:53
  • $\begingroup$ @Ihaveaquestion Well, I took your sample data and copied in a text file, then ran the code exactly as shown, just substituting the correct path, and obtained these results. I suspect that perhaps the format of the file is not as you expect it, or the numbers are not stored in a simple form. Could you share the exact contents of your data file? $\endgroup$
    – MarcoB
    Commented May 11, 2016 at 19:55
  • $\begingroup$ There are 10k lines in my text file, so I don't think I can fit that here. The elements in each line are separated by a single space, and each line has 13 elements. $\endgroup$ Commented May 11, 2016 at 19:55
  • $\begingroup$ @Ihaveaquestion Then perhaps you could show the first few here, just to make sure of format, then provide a link to the whole file (pastebin, filetea, dropbox, github, etc). $\endgroup$
    – MarcoB
    Commented May 11, 2016 at 19:56
  • $\begingroup$ replaced original question's lines with 3 actual lines from my file $\endgroup$ Commented May 11, 2016 at 19:57
0
$\begingroup$

I figured it out.

data = Import[
  "/Users/myname/Documents/foldername/filename.txt", "Table"]
Total[data, {1}]

Part of the error was that I had an empty row at the end of my text file.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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