using a list, replace multiple strings in a dataframe, without using ifelse

Viewed 23

I have multiple lists of strings, like:

list1 = c("banana","orange","kiwi")
list2 = c("jackhammer","plum","drift")

These lists reflect strings in a column in my dataframe. I am looking for a way to feed my lists into a function to replace each occurrence of these strings in my dataframe with a different string. The closest I've come uses recode, where I need to write my list out again, instead of calling my list from elsewhere:

DF$Names <- recode(DF$Names, "c('jackhammer','plum','drift') = 'misc'")

However I want to know if it's possible to call the list I already made in recode or through another function, without using ifelse. I see how to do this in ifelse but I want to learn another way.

1 Answers

I might have misunderstood, but is this what you're trying to do?

df <- data.frame(names = c("something", "plum", 
                           "something else", "kiwi"))

list1 = c("banana","orange","kiwi")
list2 = c("jackhammer","plum","drift")
df
#>            names
#> 1      something
#> 2           plum
#> 3 something else
#> 4           kiwi

df[df$names %in% c(list1, list2),] <- "misc"
df
#>            names
#> 1      something
#> 2           misc
#> 3 something else
#> 4           misc

Created on 2022-07-01 by the reprex package (v2.0.1)

Or perhaps with dplyr:

library(dplyr)

df <- data.frame(names = c("something", "plum", 
                           "something else", "kiwi"))

list1 = c("banana","orange","kiwi")
list2 = c("jackhammer","plum","drift")
df
#>            names
#> 1      something
#> 2           plum
#> 3 something else
#> 4           kiwi

combined_list <- c(list1, list2)
labels <- rep("misc", length(combined_list))
names(labels) <- combined_list
labels
#>     banana     orange       kiwi jackhammer       plum      drift 
#>     "misc"     "misc"     "misc"     "misc"     "misc"     "misc"

df$names <- recode(df$names, !!!labels)
df
#>            names
#> 1      something
#> 2           misc
#> 3 something else
#> 4           misc


# Also, labels can be anything, e.g.
df <- data.frame(names = c("something", "plum", 
                           "something else", "kiwi"))

df
#>            names
#> 1      something
#> 2           plum
#> 3 something else
#> 4           kiwi

list1 = c("banana","orange","kiwi")
list2 = c("jackhammer","plum","drift")

combined_list <- c(list1, list2)
labels <- c("a", "b", "c", "d", "e", "f")
names(labels) <- combined_list
labels
#>     banana     orange       kiwi jackhammer       plum      drift 
#>        "a"        "b"        "c"        "d"        "e"        "f"

df$names <- recode(df$names, !!!labels)
df
#>            names
#> 1      something
#> 2              e
#> 3 something else
#> 4              c

Created on 2022-07-01 by the reprex package (v2.0.1)

Related