Reputation: 27
I am trying to write a function that replaces text with another
regionChange <- function(x){
x <- sub("vic", "161", x, ignore.case = TRUE)
x <- sub("sa", "159", x, ignore.case = TRUE)
}
test <- c("vic", "sa")
regionChange(test)
test
I don't know why this function doesn't work to produce
[1] "161" "159" instead of
[1] "vic" "sa"
Do I need to write an ifelse statement? I would like to add further substitutions later on and an ifelse statement will get messy.
Upvotes: 0
Views: 43
Reputation: 70256
The result is returned invisibly because inside your function, the last function call is an assignment. If you want your function to print the result on exit, you can either tell it explicitly, like so:
> print(regionChange(test))
[1] "161" "159"
or you can change your function to one of the following:
regionChange <- function(x){
x <- sub("vic", "161", x, ignore.case = TRUE)
x <- sub("sa", "159", x, ignore.case = TRUE)
x
}
or
regionChange <- function(x){
x <- sub("vic", "161", x, ignore.case = TRUE)
sub("sa", "159", x, ignore.case = TRUE)
}
or
regionChange <- function(x){
x <- sub("vic", "161", x, ignore.case = TRUE)
x <- sub("sa", "159", x, ignore.case = TRUE)
return(x)
}
Note that, in any case (including your existing function definition), your function would properly assign its results to a vector when using
result <- regionChange(test)
Upvotes: 2
Reputation: 453
It's because you don't return X
regionChange <- function(x){
x <- sub("vic", "161", x, ignore.case = TRUE)
x <- sub("sa", "159", x, ignore.case = TRUE)
return(x)}
test <- c("vic", "sa")
test <- regionChange(test)
test
Upvotes: 2