1

I have the following table with cells containing numbers from -1 to 10 (decimal places allowed). In some cases there is a trailing A behind the number.

Now, I would like to extract all digits from the cells and calculate the average per row using a formula but only consider elements that fulfill certain conditions:

a) The header does not contain "no" and

b) the value is >= 1, otherwise the value should not count towards the average.

The expected outcome is listed in the average column.

average yes no yes yes no yes
2.75 2 2A 3.5A -1 0
2 0 4A 3A 1

I already got an very helpful answer how to solve this using an advanced formula but now I am unable to implement this (or any other) solution using openxlsx

library(openxlsx)
values <- c(2, "2A", "3A", "", "-1", "0")
values2 <- c(0, "4A", "3A", "", "", "1")
df <- rbind(values,values2)
colnames(df) <- c("yes", "no", "yes", "yes", "no", "yes")

formula <- '=LET(data,B1:G3,
     f,TAKE(data,1),
     d_,NUMBERVALUE(SUBSTITUTE(DROP(data,1),"A","")),
     BYROW(d_,LAMBDA(r,AVERAGE(FILTER(r,(f="yes")*(r>=1))))))'

wb <- createWorkbook()
addWorksheet(wb, "test")
writeData(wb, "test", x = df)
writeFormula(wb, "test", x = formula, startCol = 8, startRow = 1)
saveWorkbook(wb, "test.xlsx", overwrite = T)

When I try to open the file it say "We found a problem with some of the contents in test.xlsx". However, when I manually add the formula after the fact it works just fine.

Any help is appreciated!

5
  • 2
    See this link: modern excel formulas like lambda need a prefix. _xlfn. Commented Feb 16, 2024 at 19:12
  • @JanMarvin Thanks for your comment. So I'd need to switch to openxlsx2 or is that also possible within openxlsx? Commented Feb 16, 2024 at 20:37
  • Should be possible in openxlsx, but maybe just give it a try :) Commented Feb 16, 2024 at 20:53
  • 2
    Here’s the openxlsx2 answer: github.com/JanMarvin/openxlsx2/discussions/950 This is an array formula that needs some extensive escaping. Should work with openxlsx, but I didn’t test this. Commented Feb 19, 2024 at 7:38
  • @JanMarvin Cool, thanks! It definitely works like a charm for openxlsx2 and I appreciate you digging into this :) I did not get it to work with openxlsx, though. Commented Feb 19, 2024 at 17:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.