Google Sheet - Calculate a cost - if-statement

I'm trying to reproduce that lovely website that helps you calculate the cost of something you bought into my personnal google sheet so it's easier for me to use it.
I'm seeking here for help since I don't really know how to adapt the math when you change the value of year/month/day.
As you may see, it's able to calculate the cost by year, but when you change the value to month for example, I don't know how to make it adjust the results.
I've tried =SUMIF, =IF, but I can't seem to find a clear way to do it.
here is the doc
Thanks a lot!

I think what you are looking for is the SWITCH function:
You can in the cell D6 use the following formula:
=SWITCH(F2; I2; E1/E2; I3; E1*12/E2; I4; E1*52/E2; I5; E1*365/E2)
The logic is:
check the cell F2 (where you have the dropdown)
if the value of F2 equals I2 (Year) then, just divide the cost by the number of years
if the value of F2 equals I3 (Month), then make E1*12 and divide it by the the E2 (same as (E1/E2)/12
if the value of F2 equals I4 (Week), then calculate E1*52/E2 (same as above but with 52 weeks)
if the value of F2 equals I5 (Day), then calculate E1*365/E2 (same as above but with 365 days)
And so on on the other cells, just change the differences between the formulas, between day, week, month and year.

Related

How to take values of two different rows in Power BI?

Example: Table name - Test
Name Value
A 10
B 20
A1 30
B1 40
A2 50
B2 60
I want to make a table where I can put both values together and for only one name like below:
For name A it will take value 10 but I also want to take value 20 exact beside the value of A. Similar for A1 and A2.
Basically, I don't want names B, B1, B2 to be appear in the table but I want their values to be appear.
I know this scenario is awkward, but I have to do as per the requirement I got.
Name Value Value
A 10 20
A1 30 40
A2 50 60
If anyone knows any DAX function for this, please let me know.
Thanks for updating the sample data although it's not explaining the original data I guess. To apply logic, sample data is important. Anyway, I am giving a video link here I created based on your given data. You can take it only as a reference and apply your own best-suited logic based on your data.
Find the video Here

If x is y then z, else x without repeating x in Google Sheets

In a cell, is it possible to do if(x=y, z, x) without having to repeat x in the value_if_false argument? Whether there is a way of using if() to make this work or another function doesn't matter, and there isn't a specific formula I'm struggling with as I come across this blocker quite often (hence posting).
To help illustrate the need, if we take x as a complex or more advanced formula, such as
ARRAYFORMULA(IF(E$6:Q$6 < EoMONTH($P$4,0), "Not Active", IF(E$6:Q$6<$Q$4 + ISBLANK($Q$4) > 0,
COUNTIF({'Data'!$B$3:$B&'Data'!$I$3:$I&'Data'!$K$3:$K},$B$4&$C9&E$6:Q$6), "Not Active")))
and I wanted to put an if statement in there that changed the result only if a condition was true, the formula would more than double in size due to having to reference x twice:
=ARRAYFORMULA(IF(IF(E$6:Q$6 < EoMONTH($P$4,0), "Not Active", IF(E$6:Q$6<$Q$4 + ISBLANK($Q$4) > 0,
COUNTIF({'Data'!$B$3:$B&'Data'!$I$3:$I&'Data'!$K$3:$K},$B$4&$C9&E$6:Q$6), "Not Active"))) = 0, "No data", IF(E$6:Q$6 < EoMONTH($P$4,0), "Not Active", IF(E$6:Q$6<$Q$4 + ISBLANK($Q$4) > 0,
COUNTIF({'Data'!$B$3:$B&'Data'!$I$3:$I&'Data'!$K$3:$K},$B$4&$C9&E$6:Q$6), "Not Active"))))
This is just an example (the code is irrelevant), I'm trying to keep my formulas neat, tidy and efficient so that handing off to others is easier. Then I'm also mindful that it is calculating the same complex formula twice, which would probably slow the spreadsheet down especially when iterated throughout a spreadsheet.
Interested to hear the community thoughts and suggestions on this, hopefully I was clear in explaining it. :)
The only simple way to achieve this would be with the use of helper columns. They don't need to be in the same sheet as your main equation, but they do need to be within that same spreadsheet as a whole (ie you could have a sheet named "calc" that's specifically used to calculate intermediate steps and set "variables" by referencing those cells).
The only other option (which gets a bit complicated) is to create a custom function within Google Apps Script. For example, if you wanted to calculate (B1*A4)/C5 in multiple places, you could create a custom function like this:
/**
* Returns a calculation using cells A4, B1, and C5.
* #return A calculation using cells A4, B1, and C5.
* #customfunction
*/
function x() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('MainSheet');
var val1 = ss.getRange('B1').getValue();
var val2 = ss.getRange('A4').getValue();
var val3 = ss.getRange('C5').getValue();
return (val1*val2)/val3;
}
Then in your sheet, you could use this within a formula like this:
=if(A1="yes", x(), "no")
This custom function could obviously be altered to fit one's needs (ex taking in arguments to define the cells that the calculations should be done on instead of hard coding them, etc).
Other than this, there is currently no way to define variables within a formula itself.
This is possible to a certain extent, using TEXT's Meta Instructions, if you're using numbers and simple math conditions.
x
y
z
output
10
10
5
10
=TEXT(A3,"[="&B3&"]0;"&C3&"")
x
y
z
output
11
10
5
5
As long as your complex formula returns a number for x(or the output can be coerced to a number), this should be possible and it avoids repetition.
I agree, I would love if there was like a DECODE or NVL type function you could use so that you didn't need to repeat the original statement multiple times.
However, in many cases, when I encounter this, I can often reference another cell. Not in the way that has been suggested already, where the formula exists in another cell, but rather that the decision to perform the formula is based on another cell.
For example, using your values, lets assume the formula ((if(x=y, z, x)) only gets calculated when column 'w' is populated. Maybe column 'w' is a key component of the formula. Then you can write the formula as: if(w="",z,x). It's not exactly the same as testing the answer to the equation first and doesn't work in all situations, but in many cases I can find another field that's of key relevance to the formula that lets me get around this.

Google Sheets: I want to create a formula or function that will automatically recalculate given certain conditions

I have tried "If, and, or" combining with simple script, and I am really new at the Apps script in Google Sheets.
What I need is: if any condition is true, I want the formula/function to subtract the corresponding value only for that condition from a total.
Background: a client is expected to serve 2-3 hours a day M-F (it can vary). If M=3, T=2, W=1, TH = 3, Fri = 3, then weekly total hours (WorkHours) = 12.
But the client may not always be scheduled on any day and these nonscheduled days can vary by client location. When this occurs, I need to reduce WorkHours by the number of hours for a nonscheduled day.
For Example:
When Cell C4 = Monday and Cell C6 = x are true, that equals a nonscheduled day on Monday then the formula would only subtract Monday hours from WorkHours total = 9. But there can be multiple days, M, W and F. This can vary.
I tried the first half of this formula:
=IF(OR(AND(C4="Monday",C6="x"),AND(D4="Tuesday",D6="x"),AND(E4="Wednesday",E6="x"),AND(F4="Thursday",F6="x"),AND(G4="Friday",G6="x"))
But I can’t get the “then” half of this if-statement to work in a formula.
I tried combining it with Apps Script and I can share that, but it’s nothing to be proud of.
Thank you so much
Marby
Taking a wild guess from your data, try a SUMIFS or SUMIFformula
=SUMIFS(A4:E4,A6:E6,"")
OR
=SUMIFS(A4:E4,A6:E6,"<>x")
OR
=SUMIF(A6:E6,"",A4:E4)
(If still in need do share a test sheet or more info)
perhaps the solution to your problem is simpler than it looks, and there is no need to use scripts to make this calculation.
try to do the following way
A
B
C
1
DayWeek
isValid
TimeWorked
2
M
X
3
3
T
X
2
4
W
X
1
5
TH
3
6
F
X
3
FORMULA TO CALCULATE
=SUMIF(B2:B6;"X";C2:C6) // result 9 as example
if your spreadsheet is fed sequentially, or has multiple collaborators, I suggest you use the rows as columns.
A
B
C
D
E
F
G
H
I
J
K
1
M
3
T
2
W
1
TH
x
F
3
FORMULA
FORMULA
=sum(sumif(B1;">0";B1);sumif(D1;">0";D1); sumif(F1;">0";F1); sumif(H1;">0";H1);sumif(J1;">0";J1))
if you are sure that you will not have other numbers in the columns, the formula can be reduced to
=sum(SUMIF(A1:J1;">0";A1:J1))
Initially, none of your answers would have helped with the sheets as I had structured them. But your answers sparked a restructuring of my sheets. It made them simpler and more useful to my users.
I really appreciate all your help. It helped me improve my product. Now that my sheets have been adapted, the formula I used =SUMIFS(A4:E4,A6:E6,"<>x") - working beautifully.
I have to really thank you - you helped me improve my whole approach.
This is great, really really helpful
Marby

Google Sheet Not Multiplying in IF Formula

I am trying to calculate a price based on rates. If the number is $20,000 or below, there is a flat rate of $700. If the number is between 20,001.01 and $50,000, the rate is 3.5% of the number. The rates continue to lower as the numbers go up. I can get Google Sheets to populate the box with $700 if it is below $20,000 but I can't seem to make it do the multiplication for me. The cell just shows C4*.035
I want it to multiply the number shown in the C4 square by the percentage listed.
Here is the code as it currently sits:
=if(AND(C4<=20000),"700",IF(AND(C4>=20000.01,C4<=50000),"C4*.035", IF(AND(C4>=50000.01,C4<=100000),"C4*.0325", IF(AND(C4>=100000.01),"C4*.03"))))
Note, I know nothing about coding so I apologize if it is sloppy or doesn't make sense. I tried to copy and format based on an example that was semi similar to mine.
try:
=IF(C4<=20000, 700,
IF(AND(C4>=20000.01, C4<=50000), C4*0.035,
IF(AND(C4>=50000.01, C4<=100000), C4*0.0325,
IF(AND(C4>=100000.01), C4*0.03))))
As BigBen noticed in his comment - there's a mistake in your formula. You should not use " " around the formula if you don't want it to be read as a string.
Actually more clean solution is using IFS formula for this task.
=ifs(C4<=20000,700,
C4<=50000,C4*0.035,
C4<=100000,C4*0.0325,
C4>100000,C4*0.03)

Stata: estimating monthly weighted mean for portfolio

I have been struggling to write optimal code to estimate monthly, weighted mean for portfolio returns.
I have following variables:
firm stock returns (ret)
month1, year1 and date
portfolio (port1): this defines portfolio of the firm stock returns
market capitalisation (mcap): to estimate weights (by month1 year1 port1)
I want to calculate weighted returns for each month and portfolio weighted by market cap. (mcap) of each firm.
I have written following code which works without fail but takes ages and is highly inefficient:
foreach x in 11 12 13 21 22 23 {
display `x'
forvalues y = 1980/2010 {
display `y'
forvalues m = 1/12 {
display `m'
tempvar tmp_wt tmp_tm tmp_p
egen `tmp_tm' = total(mcap) if month1==`m' & year1==`y' & port1 ==`x'
gen `tmp_wt' = mcap/`tmp_tm' if month1==`m' & year1==`y' & port1 ==`x'
gen `tmp_p' = ret*`tmp_wt' if month1==`m' & year1==`y' & port1 ==`x'
gen port_ret_`m'_`y'_`x' = `tmp_p'
}
}
}
Data looks as shown in the image:![Data for value weighted portfolio return][1]
This does appear to be a casebook example of how to do things as slowly as possible, except that naturally you are not doing that on purpose. All it lacks is a loop over observations to calculate totals. So, the good news is that you should indeed be able to speed this up.
It seems to boil down to
gen double wanted = .
bysort port1 year month : replace wanted = sum(mcap)
by port1 year month : replace wanted = (mcap * ret) / wanted[_N]
Principle. To get a sum in a single scalar, use summarize, meanonly rather than using egen, total() to put that scalar into a variable repeatedly, but use sum() with by: to get group sums into a variable when that is what you need, as here. sum() returns cumulative sums, so you want the last value of the cumulative sum.
Principle. Loops (here using foreach) are not needed when a groupwise calculation can be done under the aegis of by:. That is a powerful construct which Stata programmers need to learn.
Principle. Creating lots of temporary variables, here 6 * 31 * 12 * 3 = 6696 of them, is going to slow things down and use more memory than is needed. Each time you execute tempvar and follow with generate commands, there are three more temporary variables, all the size of a column in a dataset (that's what a variable is in Stata), but once they are used they are just left in memory and never looked at again. It's a subtlety with temporary variables that a tempvar assigns a new name every time, but it should be clear that generate creates a new variable every time; generate will never overwrite an existing variable. The temporary variables would all be dropped at the end of a program, but by the end of that program, you are holding a lot of stuff unnecessarily, possibly the size of the dataset multiplied by about one thousand. If that temporarily expanded dataset could not all fit in memory, you flip Stata into a crawl.
Principle. Using if obliges Stata to check each observation in turn; in this case most are irrelevant to the particular intersection of loops being executed and you make Stata check almost all of the data set (a fraction of 2231/2232, almost 1) irrelevantly while doing each particular calculation for 1/2232 of the dataset. If you have more years, or more portfolios, the fraction looked at irrelevantly is even higher.
In essence, Stata will obey your instructions (and not try any kind of optimization -- your code is interpreted utterly literally) but by: would give the cross-combinations much more rapidly.
Note. I don't know how big or how close to zero these numbers will get, so I gave you a double. For all I know, a float would work fine for you.
Comment. I guess you are being influenced by coding experience in other languages where creating variables means something akin to x = 42 to hold a constant. You could do that in Stata too, with scalars or local or global macros, not to mention Mata. Remember that a new variable in Stata is an entire new column in the dataset, regardless of whether it is holding a constant or different values in each observation. You will get what you ask for, but it is more like getting an array every time. Again, it seems that you want as an end result just one new variable, and you do not in fact need to create any others temporarily at all.