Numbers in many lines:
add numbers
4900
5171
5700
4033
8583
4208
2299
2199
1699
1949
1799
2199
1899
2099
2699
2499
1549
1749
1749
2049
2149
2299
2180
2349
2499
I want to adding all this numbers. How I can do this?
Numbers in many lines:
add numbers
4900
5171
5700
4033
8583
4208
2299
2199
1699
1949
1799
2199
1899
2099
2699
2499
1549
1749
1749
2049
2149
2299
2180
2349
2499
I want to adding all this numbers. How I can do this?
My favourite method for summing a column:
Acting on a rectangle is useful because it still works as-is if the numbers are actually a column within a bunch of other text.
In more detail:
C-x* calls calc-dispatch
which has keys specifically for summing rectangles --
: and _ call calc-grab-sum-down
and calc-grab-sum-across
respectively.
Unlike calc-reduce
and friends (see below) this approach does leave the end result as a vector; so you potentially then want to calc-unpack
that with vu if the goal is to copy the final result back to the original buffer with y.
(Or simply kill/yank the value from the calc buffer using regular editing commands.)
Prior to discovering the above, my approach was to grab the rectangle from the current buffer into a calc vector, and then using the general vector operation facilities. e.g.: to sum the numbers in the marked rectangle:
calc-dispatch
calc-vector-sum
on that vector(Or as an alternative to that last step, try VR? to see the various calc-reduce
vector operations under the VR prefix.)
You've then commented:
I want to add all this numbers and then get average value
I'm guessing that by "average" you want the mean:
calc-vector-mean
on that vectorOr use some other M-x calc-vector-*
command, as desired. (Except start with x instead of M-x because calc is helpful that way. Tangentially, C-hig (calc)Help Commands
is a must-read when it comes to learning about calc
.)
C-SPC
) with point at one corner of the rectangle/column of numbers.
– phils
Jan 20 at 13:02
Wrap the numbers in (+ ...)
, that is insert (+
at the beginning and )
at the end, then hit C-x C-e (eval-last-sexp
).
(defun sum-it-up ()
"Sum the whole buffer if no active region, or just the active region (if applicable).
Copy the result to the kill ring. The result is thrown just in case anyone needs it."
(interactive)
(let* (draft
(region-active-p (region-active-p))
(reg-beg (when region-active-p (region-beginning)))
(reg-end (when region-active-p (region-end)))
(sum 0))
(save-excursion
(if reg-beg
(goto-char reg-beg)
(goto-char (point-min)))
(while (re-search-forward "[0-9,-]*\\.?[0-9]+" reg-end t)
(setq draft
(string-to-number (replace-regexp-in-string "," "" (match-string 0))))
(setq sum (+ sum draft))))
(kill-new (format "%0.2f" sum))
(message (format "%0.2f" sum))
sum))
You can also integrate other commands to help, e.g. awk
:
M-|
( shell-command-on-region
), and input awk '{s+=$1}END{print s}'
, which means summing up every lines in the region.72507
in this case.C-u M-|
.