Home > OS >  Creating functions in R
Creating functions in R

Time:01-20

I want to create a function that takes a character value x. If the value starts with the letter "A", the function should return "Apple", and so forth.

test_df <- function(x){  
  if (input 'a75'){ "apple75"   } 
  else if (input "d21"){ "dragonfruit21"   } 
  }

CodePudding user response:

Please check this below code

code

library(stringr)

test_df <- function(x){
if (str_detect(x,'^a')) {
  return('apple75')
} else if (str_detect(x,'^d')) {
  return('dragonfruit75') 
} else {
  return('no input match')
}
}

test_df('a75')

output

[1] "apple75"

CodePudding user response:

You can try something like this:

test_df <- function(x){
  x <- unlist(strsplit(x, ""))
  string <- if(x[1] == "a"){
    paste0("apple", paste0(x[-1], collapse = ""))
  } else{
    if(x[1] == "d") {
      paste0("dragonfruit", paste0(x[-1], collapse = ""))
    } 
  }
   return(string)
    
}

> test_df('a75')
[1] "apple75"
> test_df('d21')
[1] "dragonfruit21"

You can even use Vectorize and give a vector as input:

test_df_v <- Vectorize(test_df)
test_df_v(c('a75','d21', 'aZ45'))
            a75             d21            aZ45 
      "apple75" "dragonfruit21"      "appleZ45" 

Now you have a starting point, anything else you want o add, then would be easier from now on.

CodePudding user response:

test_fun <- function(x){
  x <- tolower(x) # Ensure the input is all lowercase
  if(startsWith(x, 'a')) "apple75"  
  else if (startsWith(x, 'd'))  "dragonfruit21" 
}

test_fun('A')
[1] "apple75"
  • Related