简体   繁体   中英

How can I use a list of integers as the input to a function of one integer and get a list as an output?

Apologies for asking a trivial question, but I'm stumped. Here's the situation:

  • I have a function of three inputs fishCounter(data, x, y) where data is a matrix and both x and y are integers.
  • fishCounter is in memory and works completely fine when I call it manually (eg fishCounter(matrix(1:4,4,4), 1, 4) ). Its output is a single integer.
  • The relevant data and value of x are in memory. x is simply 3, and we'll call the data trout .
  • I want R to spit out the list of results for every value of y from 1 to 20. Crudely, what I want is fishCounter(trout, 3, 1:20) .
  • The way that R gives me this data (eg array, vector, list, etc) is not of interest, I just want the output however I can get it.
  • Everything that I've tried to get this has failed. I could of course use a for loop and append this all to a vector, but that seems like far too much effort.
  • My memory insists that there is a very simple way to get what I'm after. I'm sure that some version of replicate , apply or lapply will do this job.
  • What I want is a single function that will give me this result. For example, I was surprised when lapply(c(1:19), fishCounter(trout, 3, y) didn't work.
  • No libraries should be needed and I shouldn't need to code in any new functions. My memory insists that I'm either simply forgetting a function that's build in to R, have forgotten a term that would've got me the answer instantly from a search engine, or I've completely misunderstood the documentation on the three functions that I've listed earlier.

What have I forgotten?

Maybe you can try lapply like below, ie,

lapply(1:20, function(y) fishCounter(trout, 3, y))

or Vectorize over your function fishCounter , ie,

Vectorize(fishCounter)(trout, 3, 1:20)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM