0

I have the following function

FEType <- function(NoGears  ){
    ret="Low"
    if ((NoGears == 1)   ) {ret ="Med"}
    return(ret)
}

and I call it using

df <- as.data.frame.matrix(trainingdata) 
#No.Gears is an integer
df$FEType = FEType( df$No.Gears  )

I get

Warning message in if ((NoGears == 1)) {: "the condition has length > 1 and only the first element will be used"

According to this question I need to use a vector But I am not seeing how to send a vector to my function.

Update

I was able to do the following;

FEType <- function(v  ){
    ret="Low"
    if ((v[1] == 1)   ) {ret ="Med"}
    return(ret)
}

and call it via

df$FEType = FEType( c(df$No.Gears)  

The code is less than satisfying to read. How do I do this in a more readable manner?

[Update]

One answer is to use a names vector

FEType <- function(v ,n  ){
   
    ret="Low"
    names(v ) <-n
    if ((v["NoGears"] == 1)   ) {ret ="Med"}
    return(ret)
}

I have asked here to give context to my problem.

Kirsten
  • 15,730
  • 41
  • 179
  • 318
  • I assume you want `FEType <- function(NoGears) ifelse(NoGears == 1, "Med", "Low")`. Please take a look at the linked duplicate target for help with understanding the error message. I am fairly certain that this is indeed a duplicate of the linked post. – Maurits Evers Nov 09 '20 at 01:42
  • I have edited this post quite a bit, and asked a new question as well. It is not a straight out duplicate, but most likely the question has been asked somehow already. – Kirsten Nov 09 '20 at 02:28
  • A reproducible example makes it easier for others to help you quickly and accurately . – Ronak Shah Nov 09 '20 at 03:00
  • https://stackoverflow.com/questions/64745336/how-do-i-write-a-function-in-r-to-do-cacluations-on-a-record – Kirsten Nov 09 '20 at 03:02
  • I have included an example from iris at https://stackoverflow.com/questions/64745336/how-do-i-write-a-function-in-r-to-do-cacluations-on-a-record – Kirsten Nov 09 '20 at 03:19

0 Answers0