neves
neves

Reputation: 846

Replace values with subseting operator [

I have the following data:

set.seed(1)

df_1 <- data.frame(x = replicate(n = 2, expr = sample(x = 1:3, size = 20, replace = T)), 
               y = as.factor(sample(x = 1:5, size = 20, replace = TRUE)))

I want replace the numbers >=2 by 9 in x.1 and x.2 simultaneoulsy:

df_1[df_1$x.1, df_1$x.2 >= 2] <- 9

Error in [<-.data.frame(*tmp*, df_1$x.1, df_1$x.2 >= 2, value = 9) : duplicate subscripts for columns

And replace the number 3 by 99 in y.

df_1$y[df_1$y %in% c('3')] <- 99

Warning message: In [<-.factor(*tmp*, df_1$y %in% c("3"), value = c(2L, 5L, 2L, : invalid factor level, NA generated

Tks.

Upvotes: 1

Views: 60

Answers (1)

akrun
akrun

Reputation: 887571

We can use replace

df_1[1:2] <- replace(df_1[1:2], df_1[1:2] >=2, 9)

Or another option is create the logical matrix on the subset of 'x.' columns, extract the values and assign it to 9

df_1[1:2][df_1[1:2] >= 2] <- 9

For changing the factor, we either needs to call factor again or add levels beforehand

levels(df_1$y) <- c(levels(df_1$y), "99")
df_1$y
#[1] 4 4 4 2 4 1 1 4 1 2 3 2 2 5 2 1 3 3 4 3
#Levels: 1 2 3 4 5 99

df_1$y[df_1$y == '3'] <- '99'
df_1$y
#[1] 4  4  4  2  4  1  1  4  1  2  99 2  2  5  2  1  99 99 4  99
@#Levels: 1 2 3 4 5 99

Or as @thelatemail mentioned, if we are dropping the levels while doing the replacement

levels(df_1$y)[levels(df_1$y) == '3'] <- "99"

Or can use fct_recode from forcats

library(forcats)
df_1$y <- fct_recode(df_1$y, "99" = "3")

Upvotes: 2

Related Questions