0
votes

I have a simple function:

new_function <- function(x)
 {
letters <- c("A","B","C")
new_letters<- c("D","E","F")

 if (x %in% letters) {"Correct"}
 else if (x %in% new_letters) {"Also Correct"}
 else   {x} 
 }

I make a dataframe with letters:

df <- as.data.frame(LETTERS[seq( from = 1, to = 10 )])
names(df)<- c("Letters")

I want to apply the function on the dataframe:

  df$result <- new_function(df$Letters)

And it doesn't work (the function only writes "Correct")

I get this warning:

Warning message: In if (x %in% letters) { : the condition has length > 1 and only the first element will be used

2
If the length is greater than 1, use ifelse instead of if/elseakrun
And if statement will evaluate whether the part between brackets is TRUE. If you pass a vector of letter to if (x %in% letters) {"Correct"}, this will return a vector of TRUE and FALSE value. One for each letter.P1storius
@Soren Stilling Christensen: Kindly consider to upvote or accept the answer when someone has answered your question.Saurabh Chauhan

2 Answers

1
votes

You can use lapply:

df$result <- lapply(df$Letters,new_function)

Output:

df
   Letters       result
1        A      Correct
2        B      Correct
3        C      Correct
4        D Also Correct
5        E Also Correct
6        F Also Correct
7        G            7
8        H            8
9        I            9
10       J           10
0
votes

I would rewrite your new_function with ifelse as @akrun suggested. as.character converts x to character in case it is a factor:

new_function <- function(x){
  ifelse(x %in% c("A","B","C"), "Correct",
         ifelse(x %in% c("D","E","F"), "Also Correct", as.character(x)))
}

df$result <- new_function(df$Letters)

or with case_when from dplyr:

library(dplyr)

new_function <- function(x){
  case_when(x %in% c("A","B","C") ~ "Correct",
            x %in% c("D","E","F") ~ "Also Correct",
            TRUE ~ as.character(x))
}

df %>%
  mutate(result = new_function(Letters))

Result:

   Letters       result
1        A      Correct
2        B      Correct
3        C      Correct
4        D Also Correct
5        E Also Correct
6        F Also Correct
7        G            G
8        H            H
9        I            I
10       J            J

Data:

df <- as.data.frame(LETTERS[seq( from = 1, to = 10 )])
names(df)<- c("Letters")