-1

PSA: This is in regards to a homework assignment. I'm posting here because I've tried searching StackOverflor and other resources from Google to no avail :( If you don't want to help, I understand! Just don't be mean about it please.

Hey everyone! I have a vector in a dataframe storing names c("A", "B", "C", "D", "E")

and a function accepting a parameter function(alphabet)

How do I (in one line) send each name as a parameter to a function? I want it to send each name once to the function. I've tried looking online and have realized I may have to use replicate, but I cannot figure out how to send each element as a parameter. Thanks!

Edit- as of now, I acknowledge I'm supposed to use replicate, but this is what I have- lapply(unique(df$vector), function(), USE.NAMES = TRUE)

JsDart
  • 183
  • 13
  • 2
    It's a bit unclear what you are asking and it can depend on the function you are actually calling. Most functions in R are vectorized so you just pass in the whole vector at once. Sometimes you may need to use `sapply()` to call the function multiple times. A more [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) would be helpful. – MrFlick Apr 25 '17 at 01:32
  • It's my own function (method) which accepts a name represented by each cell in the vector. It needs that parameter to do it's thing :( – JsDart Apr 25 '17 at 01:33
  • Thanks for the reply and my apologies on the vagueness! I have a dataframe; in it, I have a vector storing the names of US States accessible through df$state. I have a function that accepts strings and prints a file after analyzing the dataframe for the state. I want to, in a single line, pass each state from vector in the dataframe to the function so it analyzes each state. As there may be multiple rows having different values for a state, I am applying the unique function in my original post. – JsDart Apr 25 '17 at 01:36
  • What should I place for x? I've tried `sapply(df$state, function())` and got `Error in filter_impl(.data, dots) : argument 2 is empty`; how do I pass each element in the vector as a value to your_function(x)? – JsDart Apr 25 '17 at 01:41
  • 1
    It would be great if you can provide your function so that people can help you. – www Apr 25 '17 at 02:22

1 Answers1

0

You could use sapply():

df <- read.csv(text = "State, Some_number
Alabama, 32
Alaska, 12
Arizona, 48
Arizona, 22
Arkansas, 28
Arkansas, 30
")

my_func <- function(state) {
  paste("Function received following state:", state)
}

sapply(unique(df$State), FUN = my_func)

Results:

sapply(unique(df$State), FUN = my_func)
[1] "Function received following state: Alabama" 
[2] "Function received following state: Alaska"  
[3] "Function received following state: Arizona" 
[4] "Function received following state: Arkansas"
Community
  • 1
  • 1
Dominic Comtois
  • 10,230
  • 1
  • 39
  • 61