Reputation: 376
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
Upvotes: 0
Views: 83
Reputation: 18661
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")
Upvotes: 0
Reputation: 3221
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
Upvotes: 1