繁体   English   中英

替换R中不同文本字符串的函数

[英]function to replace different text strings in 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]用“ 161”,“ 159”代替

[1]“ vic”“ sa”

我需要写ifelse语句吗? 我想稍后再添加其他替换,否则ifelse语句将变得凌乱。

这是因为您不返回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

因为在函数内部,最后一个函数调用是赋值,所以返回的结果是看不见的。 如果希望函数在退出时打印结果,则可以明确地告诉它,如下所示:

> 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM