2016-04-21 67 views
0

我试图写一个函数与另一个功能,在R替换不同的文本字符串

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 

代替文字,我不知道为什么这个功能不工作产生

[1 “的 代替

[1]”] “161”, “159维克” 的 “sa”

我是否需要写一个ifelse语句?我想稍后再添加一些替代品,并且ifelse声明会变得混乱。

+0

你必须使用时,其分配结果向量'return' – Sotos

+0

也许最好使用'DF =数据。 frame(name = c('vic','sa'),number = c(161,159))''而不是'df $ number [match(c('vic','sa'),df $ name)]'for这个目的。 –

回答

2

那是因为你不回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 
2

返回结果无形之中,因为你的函数里面,最后一个函数调用的分配。如果你希望你的函数打印出结果,你可以明确告诉它,就像这样:

> print(regionChange(test)) 
[1] "161" "159" 

,或者你可以改变你的函数来执行下列操作之一:

regionChange <- function(x){ 
    x <- sub("vic", "161", x, ignore.case = TRUE) 
    x <- sub("sa", "159", x, ignore.case = TRUE) 
    x 
} 

regionChange <- function(x){ 
    x <- sub("vic", "161", x, ignore.case = TRUE) 
    sub("sa", "159", x, ignore.case = TRUE) 
} 

regionChange <- function(x){ 
    x <- sub("vic", "161", x, ignore.case = TRUE) 
    x <- sub("sa", "159", x, ignore.case = TRUE) 
    return(x) 
} 

注意,在任何情况下(包括现有的函数定义),你的函数会正确使用

result <- regionChange(test)