Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
具有多列和数据帧的函数gsub R_R_For Loop_Gsub - Fatal编程技术网

具有多列和数据帧的函数gsub R

具有多列和数据帧的函数gsub R,r,for-loop,gsub,R,For Loop,Gsub,我有两个列名称相同的数据帧。我想替换多个数据帧的两列中的某个表达式。因此,我编写了以下代码: dat <- data.frame(n = 1:19, des = c("Some very long text", "Some very lang test", "Some vary long text", "Some veri long text", "Another very long text", "Anather very long text", "Another very long t

我有两个列名称相同的数据帧。我想替换多个数据帧的两列中的某个表达式。因此,我编写了以下代码:

dat <- data.frame(n = 1:19, des = c("Some very long text", "Some very lang test", "Some vary long text", "Some veri long text", "Another very long text", "Anather very long text", "Another very long text", "Different text", "Diferent text", "More text", "More test", "Much more text", "Muh more text", "Some other long text", "Some otoher long text", "Some more text", "Same more text", "New text", "New texd"), x = c("other text", "bad text", "wrong text", "very bad text", "very nice text","text", "text", "text", "text", "text", "text", "text", "text", "text", "text", "text", "text", "text", "text"))

dat1 <- data.frame(n = 1:5, des = c("very Some long text", "text Some very long", "Some very long text", "long text Some very", "very long Some text"), x = c("crazy text", "very crazy text", "boring text", "very exciting text","ext"))

repla <- function(dat){
vari <- c(which(names(dat) == "x"),which(names(dat) == "des"))
    for (i in vari){
    dat[,i] <<- gsub("very", "0", dat[,i])
    }
}

dat将函数定义更改为:

repla <- function(dat){
vari <- c(which(names(dat) == "x"),which(names(dat) == "des"))
    for (i in vari) {
        # don't use the parent scope assignment operator here
        # instead, just modify the local variable
        dat[,i] <- gsub("very", "0", dat[,i])
    }

    # return modified data frame to the caller
    return(dat)
}
dat1 <- repla(dat1)
> dat1
  n              des               x
1 1 0 Some long text      crazy text
2 2 text Some 0 long    0 crazy text
3 3 Some 0 long text     boring text
4 4 long text Some 0 0 exciting text
5 5 0 long Some text             ext