how to do nested if in power bi - powerbi

Hi I have this code but doesn't seem to work, can't find what the error is.
MA2 = IF(AND('Rawdata'[Country]<>"AU",'Rawdata'[Country]<>"NZ"),"",IF(or(' Rawdata'[Country]="AU",'Rawdata'[Country]="NZ"),LOOKUPVALUE(Sheet1[Manual Allocation],Sheet1[Material],'Rawdata'[SKU]),"No"))
what im trying to do is:
if country is not AU and NZ, return "", if country is AU and NZ, and the material exists in sheet1, return manual allocation column from sheet1, otherwise return "No"
thanks in advance

Try this one.
MA2 =
IF(
NOT 'Rawdata'[Country] IN {"AU","NZ"}
,""
,LOOKUPVALUE(
Sheet1[Manual Allocation]
,Sheet1[Material]
,'Rawdata'[SKU]
,"No"
)
)

Related

ABC analysis without aggregation

I never use DAX and I find it very complicated!
I read this https://www.daxpatterns.com/abc-classification/ but I find it complicated.
My dataset is like this https://1drv.ms/x/s!AvMy-Bzzx3mqgwmKSZm6wr_W4VXr?e=Jwwbji&nav=MTVfezAwMDAwMDAwLTAwMDEtMDAwMC0wMDAwLT...
I need to sum column Value if the Name and date are the sums after doing the ABC analysis. The problem is that I can't aggregate before in transform because I need the column Name Fatt!
It is not necessary for a dynamic ABC analysis. The value for each Name and Date is the same...
I appreciate every help! Also video tutorial or something can help me. Thanks!
'Aggregazione fatturato = SUMX(UNION(VALUES(Name),VALUES(Date)),SUM(Value)
Fatturato Cumulato =
VAR CurrentProductSales = 'Misure'[Aggregazione fatturato]
VAR BetterProducts =
FILTER (
Name,
'Misure'[Aggregazione fatturato] >= CurrentProductSales
)
VAR Result =
SUMX (
BetterProducts,
'Misure'[Aggregazione fatturato]
)
RETURN
Result
Cumulated Pct =
DIVIDE (
'Misure'[Fatturato Cumulato],
SUM ('Misure'[Aggregazione fatturato])
ERROR 'Misure'[Aggregazione fatturato] not found

Power bi returning value based on multiple condition

I have the data below
create table #data (Post_Code varchar(10), Internal_Code varchar(10))
insert into #data values
('AB10','hb3'),('AB10','hb25'),('AB12','dd1'),('AB15','hb6'),('AB16','aa4'),('AB16','hb7'),
('AB16','aa2'),('AB16','ab9'),('AB18','rr6'),('AB18','rr9'),('AB18','hb10'),('AB20','rr15'),
('AB20','td2'),('AB21','hb8'),('AB21','cc4'),('AB21','cc4'),('AB24','td5'),('AB9','yy3'),
('RM2','CC1'),('RM6','hb6'),('RM7','cc2'),('SA24','rr1'),('SA24','hb5'),('SA24','rr2'),
('SA24','cc34'),('SE15','rr9'),('SE15','rr5'),('SE25','rr10'),('SE25','hb11'),('SE25','rr8'),
('SE25','rr1'),('LA15','rr2')
select * from #data
drop table #data
What I want to achieve is if the same post code area have “hb” or “rr” in the same post code I want to return 1 else 0
The “hb” or “rr” internal_code must be in the same post_code if they in different post code. It should be 0
I wrote this DAX
Result = IF(left(Data[Internal_Code],2)="hb" || left(Data[Internal_Code],2)="rr",1,0)
it is not returning the correct result
current output
expected output
I think your expected result is incorrect as SA24 should also be 1. You should definitely do a calculation like this in PQ but if you need to do it in DAX in a calculated column, then use the following code which works.
Result =
VAR post_code = Data[Post_code]
RETURN
VAR hb = CALCULATE (COUNTROWS(Data),'Data'[Post_code] = post_code && left(Data[Internal_Code],2) = "hb" )
VAR rr = CALCULATE (COUNTROWS(Data),'Data'[Post_code] = post_code && left(Data[Internal_Code],2) = "rr" )
RETURN IF(hb>0 && rr > 0,1)

Occurrences of a value in a table in Power BI

I got articles from PubMed, I am using Power BI to visualise How many articles are written by each author, each article is written by many authors as shown in the picture any idea to do that, this is my table structure in power bi. What I want to get is a chart visualising :
name of author: number of articles
One other thing is to visualise collaboration between authors, I mean how many time each pair of authors worked together,
any ideas, I searched about it but not result that I need just an orientation.
First if you want to show how many article writes a specific author then you need a list of authors in one column (if you dont have dictionary then you can create this list as NewTable in dax):
AuthorsList = SUMMARIZE(UNION( VALUES(pubmed[name1]), VALUES(pubmed[name2]), VALUES(pubmed[name3])), pubmed[name1])
Then we can create a measure:
ArticleCount =
var __author = SELECTEDVALUE(AuthorsList[name1])
return
CALCULATE( COUNTROWS(VALUES(pubmed[ID])), FILTER(ALL(pubmed), pubmed[name1] = __author || pubmed[name2] = __author || pubmed[name3] = __author))
And for collaboration, I think we can create a cross join ListOfAuthors and use measures like this one (but I don't test it).
ArticleCount =
var __author = SELECTEDVALUE(AuthorsList[name1])
var __author2 = SELECTEDVALUE(AuthorsList[name2])
var __author3 = SELECTEDVALUE(AuthorsList[name3])
return
CALCULATE( COUNTROWS(VALUES(pubmed[ID])), FILTER(ALL(pubmed),
(pubmed[name1] = __author || pubmed[name2] = __author || pubmed[name3] = __author) &&
(pubmed[name1] = __author2 || pubmed[name2] = __author2 || pubmed[name3] = __author2) &&
(pubmed[name1] = __author3 || pubmed[name2] = __author3 || pubmed[name3] = __author3)
)
)

Implementing Binomial Hypothesis Testing significance tests in Power BI (DAX)

This is partly a theory question, and partly an implementation question. My stats is a little rusty...
I am developing a report that is attempting to determine if the difference in occurances between a reference group and a selected group are statistically significant.
So, for example, if something occurs in X of n tests for one group, is it statistically significant than if it 'normally' occurs at a rate of Y of m tests for a different (control) group.
So, my H0 is that the rate is Y of m, per the control group
h1 is that it is not the same as the control group. (ideally, I'd like to use a 1-tailed test, depending if the observed occurrence is greater or less than the control, but my current implementation is 2 tailed)
I'd be comfortable with a CI of 80%.
I've got (slightly pseudocode here):
Zscore =
VAR pControl = DIVIDE(COUNT([Control occurrences]), COUNT([Control Tests])) RETURN
VAR pTest = DIVIDE(COUNT([Test occurrences]), COUNT([Test Tests])) RETURN
VAR controlStandardError =
SQRT(
DIVIDE(
(pControl * (1-pControl)
, COUNT([Control Tests])
)
) RETURN
VAR testStandardError =
SQRT(
DIVIDE(
(pTest* (1-pTest)
, COUNT([Test Tests])
)
) RETURN
DIVIDE(
(pTest - pControl)
, SQRT(POWER(testStandardError, 2) + POWER(controlStandardError, 2)
)
I'm then calculating:
p-Value =
VAR pControl = DIVIDE(COUNT([Control occurrences]), COUNT([Control Tests])) RETURN
IF(pControl > 0,
1 - ABS(NORM.DIST(Zscore, 0, 1, TRUE)
)
I am then displaying in a table each of my non-null hypotheses and filtering the table such that p-Value is less than 0.1. (2-tailed 80%)
am I on the right track here? Or have I completely bungled the theory on this one?
Theory and example tables - Right-tailed (μ > μ₀)
DAX
ControlGroup
XControl = COUNTROWS(FILTER(ControlGroup,ControlGroup[Outcome]=1))
NControl = COUNTROWS(ControlGroup)
pControl = DIVIDE([XControl],[NControl])
TreatmentGroup
XTreatment = COUNTROWS(FILTER(TreatmentGroup,TreatmentGroup[Outcome]=1))
NTreatment = COUNTROWS(TreatmentGroup)
pTreatment = DIVIDE([XTreatment],[NTreatment])
Test Parameters
PooledProportion =
DIVIDE(
[XTreatment]+[XControl],
[NTreatment]+[NControl]
)
ZCritivalValue = NORM.S.INV(0.90)
ZValue = DIVIDE(
[pTreatment]-[pControl],
SQRT(
[PooledProportion]*(1-[PooledProportion])*((1/[NTreatment])+(1/[NControl]))
)
)
Visualization (example)

How to resize tables generated by Stargazer in R Markdown?

I included resize.height=0.5,resize.width=0.5 in the code chunk, but still can't resize the table generated by stargazer. Can anyone tell me why?
My code chunk options look like this:
echo=FALSE,warning=FALSE,results='asis',resize.height=0.5,resize.width=0.5}
The stargazer codes are like this:
stargazer(did.student,student.control.kmt,student.control.neu,student.control.dpp,header = FALSE,
title="DD Model",
covariate.labels = c("Treatment","group","Treatment*group"),
dep.var.labels = "attitude",
column.labels = c("","party1","Independent","party2"),
label = "DiD-students")
Would appreciate any help!
--
Forgot to mention - I'm using beamer with the table.
I kind of solve the problem myself:
To adjust table size with stargazer, you can change the font size font.size=, make the Stargazer single row single.row = TRUE and change the space between columns column.sep.width = "1pt" in stargazer().
Though the link here suggests using print(stargazer(),scalebox='0.7'), it doesn't work for me perhaps because I'm using Markdown with Beamer, but I'm not sure. Would still love to have more contribution on this.
I was hoping for a more straightforward answer, but this works!
This comment on GitHub inspired me to implement \resizebox{} into stargazer(). You can use resizebox.stargazer() to specify the size of the table outputted from stargazer() with tab.width and/or tab.height arguments. To activate the function, you need to run the following code first:
resizebox.stargazer = function(..., tab.width = "!", tab.height = "!"
){
#Activate str_which() function:
require(stringr)
#Extract the code returned from stargazer()
res = capture.output(
stargazer::stargazer(...)
)
#Render the arguments:
tab.width = tab.width
tab.height = tab.height
#Attach "}" between \end{tabular} and \end{table}
res =
prepend(res, "}", before = length(res))
#Input \resizebox before \begin{tabular}
res =
c(res[1:str_which(res, "^\\\\begin\\{tabular\\}.*")-1],
paste0("\\resizebox{",tab.width,"}{",tab.height,"}{%"),
res[str_which(res, "^\\\\begin\\{tabular\\}.*"):length(res)]
)
#Produce the whole strings
cat(res, sep = "\n")
}
You can specify the table size by e.g. resizebox.stargazer(..., tab.width = "0.7\\textwidth"). Note that you have to write the TeX commands from \\ instead of \.
I would follow #yuan-ning and manipulate the options of stargazer. Try the following for PDF output of R markdown:
stargazer(model_1, model_2, model_3, model_4, model_5,
type = 'latex',
header=FALSE, # to get rid of r package output text
single.row = TRUE, # to put coefficients and standard errors on same line
no.space = TRUE, # to remove the spaces after each line of coefficients
column.sep.width = "3pt", # to reduce column width
font.size = "small" # to make font size smaller
)
Here is an alternative to Carlos' solution that writes the output to a LaTeX file:
mkTexTable <- function(..., file){
tbl <- capture.output({
stargazer(...)
})
tbl <- gsub("\\begin{tabular}", "\\resizebox{\\textwidth}{!}{\\begin{tabular}", tbl, fixed = T)
tbl <- gsub("\\end{tabular}", "\\end{tabular}}", tbl, fixed = T)
fileConn <- file(file)
writeLines(tbl, fileConn)
close(fileConn)
}
mkTexTable(lm1, lm2, "texOutput.tex")
This post also provided some help: https://stackoverflow.com/a/36018251/2289444
If the problem is with html Rmd files, you sould specify {r, results = 'asis'} at the beginning of the chunck and then in stargazer type = 'html'. That worked for me.