Krisselack
Krisselack

Reputation: 511

change argument object in R

I want to mutate a data.frame object within a function. The following does not do what I intended:

# function to change factors to characters using dplyr
# x: a data.frame
fa_clean <- function(x,...) {
  require(dplyr)
  x <- x %>% mutate_if(is.factor, as.character) 
  print(x)
  return(x) 
 }

# example set 
test <- data.frame(number=c(1:10),letter=as.factor(letters[1:10]))

fa_clean(test) # applying the function 
str(test) # letter is still a factor ??? 

I am obviously missing something. Edit: And I am aware of:

test <- fa_clean(test)

But I would like to run it without this assignment.

Upvotes: 0

Views: 358

Answers (1)

s_baldur
s_baldur

Reputation: 33488

Here is your code with the necessary modification to make it work:

fa_clean <- function(x) {
  varname <- deparse(substitute(x))
  require(dplyr)
  x <- x %>% mutate_if(is.factor, as.character) 
  assign(varname, x, envir = .GlobalEnv)
}

# example set 
test <- data.frame(number=c(1:10),letter=as.factor(letters[1:10]))
fa_clean(test)
str(test) # letter is no longer a factor
'data.frame':   10 obs. of  2 variables:
 $ number: int  1 2 3 4 5 6 7 8 9 10
 $ letter: chr  "a" "b" "c" "d" ...

Upvotes: 1

Related Questions