Posts

Showing posts with the label sum

Simultaneously sum two keys in list of dicts by multiple items

Image
Clash Royale CLAN TAG #URR8PPP Simultaneously sum two keys in list of dicts by multiple items I want to sum two different variables in one function, but I want these to be summed based on multiple other items. If I have the following list of dicts x: x=[{'id':1, 'var1':'a', 'var2':'left', 'var3':0.1, 'var4':1}, {'id':2, 'var1':'a', 'var2':'right', 'var3':0.1, 'var4':1}, {'id':2, 'var1':'a', 'var2':'right', 'var3':0.2, 'var4':3}, {'id':4, 'var1':'b', 'var2':'left', 'var3':0.4, 'var4':4}, {'id':5, 'var1':'b', 'var2':'right', 'var3':0.1, 'var4':5}, {'id':5, 'var1':'b', 'var2':'right', 'var3':0.4, 'var4':2}] Then i can use the following function...

RowSums conditional on value

Image
Clash Royale CLAN TAG #URR8PPP RowSums conditional on value I'm rather new to r and have a question that seems pretty straight-forward. I want to do rowSums but to only include in the sum values within a specific range (e.g., higher than 0). e.g. - with the last column being the requested sum col1 col2 col3 col4 totyearly 1 -5 3 4 NA 7 2 1 40 -17 -3 41 3 NA NA -2 -5 0 4 NA 1 1 1 3 What I currently have is: df$totyearly <- rowSums(df[, 1:4], na.rm=TRUE) How do I add the condition re positive values? 2 Answers 2 We can use replace to replace the values less than 0 to 0 and then take rowSums . replace rowSums df$totyearly <- rowSums(replace(df, df < 0, 0), na.rm = TRUE) df # col1 col2 col3 col4 totyearly #1 -5 3 4 NA 7 #2 1 40 -17 -3 41 #3 NA NA -2 -5 0 #4 NA 1 ...

sum for unique value of particular column and print

Image
Clash Royale CLAN TAG #URR8PPP sum for unique value of particular column and print I have a file in the following format: a|x|ahjkd|1 a|y|abd|2 b|x|tuj|3 b|gf|hui|4 I want the sum of column 4 for every unique value in column 1 and print all the lines along with the sum for corresponding column 1 i.e. output should be like a|x|ahjkd|1|3 a|y|abd|2|3 b|x|tuj|3|7 b|gf|hui|4|7 What have you tried so far? – Ben Jones Jul 19 at 19:34 Did you consider a particular programming / scripting language to achieve this? – πάντα ῥεῖ Jul 19 at 19:36 i want to do it using awk arrays – user6677057 J...