I have a vector of strings like for example jk <- c("abc", "lkg", "mno", "ike")
and a data frame df
that looks like
names nos
abc 1
pqe 2
mno 3
Where first I convert the string in the names
column to character strings by using as.character(df$names)
I want to check if the string in column is contained into vector jk
So, I wrote a function as below
res <- function(p) {
if(grep(p, jk, fixed=TRUE) > 0) {
return(1)
else {
return(0)
}
}
The desired output should be as follows
names nos res
abc 1 1
pqe 2 0
mno 3 1
But when I perform the following function call
df$res <- lapply(df$names, FUN=res)
I get the following error
Error in if (grep(p, jk, fixed=TRUE) > 0) { : argument is of length zero
when I do the following function call
df$res <- apply(df$names, M FUN=res)
I get the following error.
Error in apply(X = d$names, MARGIN = 1, FUN = res) : dim(X) must have a positive length
How do I get the desired output? Please help!