Say I have a dataframe:
set.seed(10)
col_a <- (c("mouse", "dog", "rabbit", "cat", "horse", "monkey", "pig", "shark", "flea","ant"))
col_b <- (c(round(rnorm(10), digits=0)))
col_c <- (c(round(rnorm(10), digits=0)))
col_d <- (c(round(rnorm(10), digits=0)))
col_e <- (c(round(rnorm(10), digits=0)))
df <- data.frame(col_a, col_b, col_c, col_d, col_e)
df
col_a col_b col_c col_d col_e
> 1 mouse 0 0 0 0
> 2 dog 0 0 0 1
> 3 rabbit -2 0 -1 -1
> 4 cat 0 0 1 0
> 5 horse 1 2 0 0
> 6 monkey 1 1 -1 1
> 7 pig 0 -1 0 1
> 8 shark -2 0 0 -1
> 9 flea 0 1 0 0
> 10 ant 0 2 1 1
>
and I want to replace the values in “col_b” and “col_d” corresponding to “shark” in with those of “mouse”. I want to index using the column headers and the values in col_a.
I can do this in two steps with:
df[df$col_a == “shark”, “col_b”] <- df[df$col_a == “mouse” , “col_b”]
df[df$col_a == “shark”, “col_d”] <- df[df$col_a == “mouse” , “col_d”]
With many columns the code becomes quite clunky. Is there a way to streamline this with a for loop or the apply function?