Search code examples
rlistreplaceformulasoutliers

Replace values in a vector in R


all.

I need to replace a specific value (an outlier) in a vector in R by the vector mean (one other suggestion in this case would be appreciated). I would like to use the R-function "replace" to do so, but I´m still a beginner and I´m getting an error I can´t fix by myself. This is what I´m trying:

replace(data$students, outlier, mean(data&students))

Someone told me in another post that I can`t use & for formulas, so perhaps that´s the problem, but at the same time this is the error I´m getting:

 invalid subscriptor type 'list'

This means I must create a list before typing the replace function? what should I type?

Sorry for the basic information, but I just started with R. Thanks a lot for your nice responses.


Solution

  • If the outlier detection is based on values greater than 2000, then

    data$students <- with(data, replace(students, students > 2000, mean(students)))
    

    Regarding the mean part, it is not clear whether the mean takes the outlier values too. If it is not

    i1 <- data$students >2000
    data$students <- with(data, replace(students, i1, mean(students[i1])))