2016-04-21 34 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)