0

When doing nested maps in R, I often need to make a small change to an input before it goes into the next map. In that case, I don't want to write a function for it, because it's a very small change, but I can't fit it into one pipe call. Is there any way to do an assignment within an anonymous function, then feed that into the next map?

# Reprex

data = list(
  `3` =list(
    '1' <- c(1, 2),
    '2' <- c(3,4)
  ),
  `4` = list(
    '3' <- c(5,6),
    '4' <- c(7,8)
  ) 
)

# Sum up the element of each list, and then add the name of the list to the sum.
imap(data, function(stuff, name) map(stuff, function(x) sum(x) + as.numeric(name)))

# But what if I want to change the value of the name before feeding into next map?

imap(data, function(stuff, name) name = 2 * as.numeric(name) 
map(stuff, function(x) sum(x) + as.numeric(name)))

This gives the error:

Error: unexpected symbol in "imap(data, function(stuff, name) name = 2 * as.numeric(name) map"

I've also tried using brackets in different places, and continue to get the same error.

Jesse Kerr
  • 341
  • 1
  • 8
  • 5
    Possibly. But there's no way to know for sure and give you a relevant answer without a concrete example. – r2evans Aug 14 '19 at 15:35
  • 2
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. It's a bit too unclear what exactly you need to do. – MrFlick Aug 14 '19 at 15:35
  • Thank you for the advice, I've edited my question. – Jesse Kerr Aug 14 '19 at 16:12
  • 1
    If your function body has more than one expression, you need to wrap it in braces. For example `imap(data, function(stuff, name) {name = 2 * as.numeric(name); map(stuff, function(x) sum(x) + name)})` – MrFlick Aug 14 '19 at 16:53
  • Thank you @MrFlick! I tried the braces, but I did not know about the need for the semicolon in R. Now I'm noticing that this works if I add a new line or a semicolon, but does not otherwise, even with the braces. Do you know why that is? – Jesse Kerr Aug 14 '19 at 17:13
  • 2
    The R parser expects only one expression per line. If you have multiple expressions on the same line, you need to separate them with a semi colon. Normally I would just use a new line but the comments section on this site doesn't make it easy to format multi-line code chunks. – MrFlick Aug 14 '19 at 17:56

0 Answers0