Dan Chaltiel
Dan Chaltiel

Reputation: 8493

Replacing empty values with plyr::revalue

I have a vector in which I want to replace some values, based on another vector.

I use plyr::revalue for this :

x = c("a", "b", "c", "d", "", "  ", "d, ", "aaaaa")
var.replace = c("d"=NA, "a"="A")
x %>%  plyr::revalue(var.replace)
#[1] "A"      "b"      "c"      NA       ""       "  "     "d, "    "aaaaa"
var.replace = c("d"=NA, "a"="A", ""=NA)
#Error: attempt to use zero-length variable name

I know there is an accepted answer in the question One of the factor's levels is an empty string; how to replace it with non-missing value?, but I'm looking for an elegant one-liner, in the tidyverse spirit.

Does one exists ?

Upvotes: 1

Views: 691

Answers (3)

Dan Chaltiel
Dan Chaltiel

Reputation: 8493

Akrun answer made me figure it out ! It happens that you just have to omit the key for the name to be empty :

> setNames(c(NA, "A", NA), c("d", "a", ""))
#  d   a     
# NA "A"  NA 
> c("d"=NA, "a"="A", NA)
#  d   a     
# NA "A"  NA

Then, the formula become very simple :

var.replace = c("d"=NA, "a"="A", NA)
x %>%  revalue(var.replace)

Upvotes: 3

akrun
akrun

Reputation: 887291

We can use setNames to create "" as names and then do the revalue

var.replace <- setNames(c(NA, "A", NA), c("d", "a", ""))
x %>%
    plyr::revalue(var.replace)
#[1] "A"     "b"     "c"     NA      NA      "  "    "d, "   "aaaaa"

Upvotes: 2

Sotos
Sotos

Reputation: 51592

You can use replace to deal with empty elements and then revalue as usual, i.e.

replace(x, x == '', NA) %>% plyr::revalue(var.replace)
#[1] "A"     "b"     "c"     NA      NA      "  "    "d, "   "aaaaa"

Upvotes: 3

Related Questions