user213544
user213544

Reputation: 2126

Renaming factor levels using a subset of the factor self in R

I have a sample factor:

x <- factor(c("alpha", "beta", "gamma", "alpha", "beta"))

# Output
> x
[1] alpha beta  gamma alpha beta 
Levels: alpha beta gamma

The factor levels can be renamed in several ways (described here in the Cookbook for R). The revalue() function of the plyr library is an option:

library(plyr)
revalue(x, c("beta" = "two", "gamma"="three"))

# Output   
> revalue(x, c("beta" = "two", "gamma"="three"))
[1] alpha two   three alpha two  
Levels: alpha two three

Problem

I would like to use the revalue() function inside a function, so I thought it would be possible to use subsetting of the factor in the revalue() function:

revalue(x, c(x[2] = "two", x[3]="three"))

This produces the following error:

Error: unexpected '=' in "revalue(x, c(paste(x[2]) ="

Next, I tried the paste() function:

revalue(x, c(paste(x[2]) = "two", x[3]="three"))

Sadly, with the same error.

Question

What is happening here? Since paste(x[2]) equals "beta", I thought it should work?

Upvotes: 2

Views: 105

Answers (2)

Jonny Phelps
Jonny Phelps

Reputation: 2717

c() doesn't like it for some reason. Can always assign names after e.g.

y <- c("two", "three")
names(y) <- x[2:3]
revalue(x, y) 

Upvotes: 0

akrun
akrun

Reputation: 886938

We can use setNames

plyr::revalue(x, setNames(c("two", "three"), x[2:3]))
#[1] alpha two   three alpha two  
#Levels: alpha two three

Note that

setNames
function (object = nm, nm) 
{
    names(object) <- nm
    object
}

Or another option is fct_recode

library(forcats)
fct_recode(x, two = as.character(x[2]), three = as.character(x[3]))
#[1] alpha two   three alpha two  
 #Levels: alpha two three

Upvotes: 1

Related Questions