Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sum values in column based on the value in another column?

I have a text file which is:

ABC 50
DEF 70
XYZ 20
DEF 100
MNP 60
ABC 30

I want an output which sums up individual values and shows them as a result. For example, total of all ABC values in the file are (50 + 30 = 80) and DEF is (100 + 70 = 170). So the output should sum up all unique 1st column names as -

ABC 80
DEF 170
XYZ 20
MNP 60

Any help will be greatly appreciated.

Thanks

like image 896
Sam Avatar asked Feb 22 '10 13:02

Sam


People also ask

How do I sum cells based on value in another cell?

For example, the formula =SUMIF(B2:B5, "John", C2:C5) sums only the values in the range C2:C5, where the corresponding cells in the range B2:B5 equal "John." To sum cells based on multiple criteria, see SUMIFS function.

How do you sum values based on two criteria in another column in Excel?

If you need to sum numbers based on multiple criteria, you can use the SUMIFS function. The first range (D4:D11) are the cells to sum, called the "sum range". Criteria are supplied in pairs... (range / criteria).

How do you sum a column based on another column in R?

How to find the sum of a column values up to a value in another column in R? To find the sum of a column values up to a particular value in another column, we can use cumsum function with sum function.


4 Answers

$ awk '{a[$1]+=$2}END{for(i in a) print i,a[i]}' file
ABC 80
XYZ 20
MNP 60
DEF 170
like image 147
ghostdog74 Avatar answered Oct 24 '22 17:10

ghostdog74


$ perl -lane \
    '$sum{$F[0]} += $F[1];
     END { print "$_ $sum{$_}"
             for sort grep length, keys %sum }' \
    input
ABC 80
DEF 170
MNP 60
XYZ 20
like image 32
Greg Bacon Avatar answered Oct 24 '22 16:10

Greg Bacon


awk '{sums[$1] += $2} END { for (i in sums) printf("%s %s\n", i, sums[i])}' input_file | sort

if you don't need the results sorted alphabetically, just drop the | sort part.

like image 41
ggiroux Avatar answered Oct 24 '22 18:10

ggiroux


perl -lane '$_{$F[0]}+=$F[1]}print"$_ $_{$_}"for keys%_;{' file

And a little bit less straightforward:

perl -ape '$_{$F[0]}+=$F[1]}map$\.="$_ $_{$_}\n",keys%_;{' file
like image 33
codeholic Avatar answered Oct 24 '22 18:10

codeholic