Shawn
Shawn

Reputation: 3369

R: Use replace function with multiple index criteria

Is there a way to handle multiple conditionals at once using replace?

What I have now is a data.frame and want to keep it a data.frame:

names$first <- replace(names$first, names$first=="kevin", "Kevin")

works fine, but I want to be able to handle multiple criteria by avoiding if_else if possible. Is something like the below possible? The documentation is sparse and has no examples.

names$first <- replace(names$first, c("kevin","susan"), c("Kevin","Susan"))

Upvotes: 1

Views: 242

Answers (3)

G. Grothendieck
G. Grothendieck

Reputation: 269654

Here are some ways assuming this input:

from <- c("kevin", "susan")
to <- c("Kevin", "Susan")
Names <- data.frame(first = c("kevin", "susan", "joe"), stringsToFactors = FALSE)

1) match This is a base R solution:

first <- Names$first
From <- c(from, first)
To <- c(to, first)
Names$first <- To[match(first, From)]

The above could be written as one line but might not be as clear.

2) gsubfn

library(gsubfn)
Names$first <- gsubfn(".*", as.list(setNames(to, from)), Names$first)

3) Reduce This one does use replace. It is also a base R solution.

repl <- function(x, i) replace(x, x == from[i], to[i])
Names$first <- Reduce(repl, init = Names$first, seq_along(from))

4) for A for loop is another base solution and uses replace and is simple:

for(i in seq_along(from)) {
    Names$first <- with(Names, replace(first, first == from[i], to[i]))
}

Upvotes: 1

Andrew Lavers
Andrew Lavers

Reputation: 4378

library(stringr)    
names = data.frame(first = c("kevin", "susan", "anbreen"))
str_replace_all(names$first, c("kevin" = "Kevin", "susan" = "Susan"))

#[1] "Kevin"   "Susan"   "anbreen"

Upvotes: 2

smanski
smanski

Reputation: 541

The second argument in replace is an index vector. What you would need here is something like

kevins <- which(names$first == "kevin")
susans <- which(names$first == "susan")
replace(names(first), c(kevins, susans),
        c(rep("Kevin", length(kevins)), rep("Susan", length(susans))))

But like @epi99 said, there are packages with functions to do this, if you don't mind leaving base R. I hope this helps!

Upvotes: 1

Related Questions