mutate replace, how to specify as character

2764 views r

I have this data in which I want to replace "20-Oct" with "10-20" in column "depth". Depth is a factor here.


This is what I tried:

BNPP <- BNPP %>%
  mutate(depth = replace(depth, depth == "20-Oct", "10-20"))

And I got this error message:

Warning message:
In `[<-.factor`(`*tmp*`, list, value = "10-20") :
  invalid factor level, NA generated

So I tried to fix it by doing this:

BNPP <- BNPP %>%
  BNPP$depth <- as.character(BNPP$depth) %>%
  mutate(depth = replace(depth, depth == "20-Oct", "10-20"))

And I got a different error message:

 Error in UseMethod("mutate_") : 
      no applicable method for 'mutate_' applied to an object of class "character"

I tried putting the as.character outside the code chunk and it worked, but I have no idea why:

BNPP$depth <- as.character(BNPP$depth)
BNPP <- BNPP %>%
  mutate(depth = replace(depth, depth == "20-Oct", "10-20"))

I would appreciate an explanation for why the first one doesn't work but the last one works.

answered question

1 Answer


This looks like an excel auto-correct issue( which is hilarious by the way).

The error message tells you that "10-20" is not in the levels(BNPP$depth), so you can't directly mutate "20-Oct" to something else.

An easy fix is to convert BNPP$depth as a Character vector, then mutate it: (During the test I find that mutate+gsub will do the conversion for you)


# data
df <- data.frame(
  plot = c(1,1,1),
  subplot = c("B","B", "B"),
  depth = c("0-10","20-Oct", "20-30")

# mutate depth <-
  df %>%
  mutate(depth = gsub("20-Oct","10-20", depth))
#>   plot subplot depth
#> 1    1       B  0-10
#> 2    1       B 10-20
#> 3    1       B 20-30

Created on 2018-11-05 by the reprex package (v0.2.1)

posted this

Have an answer?


Please login first before posting an answer.