Replace Values in Vector on Specific Place in R

I want to make $5^{th}$,$10^{th}$,$15^{th}$,$20^{th}$ and $25^{th}$ values of vector an outlier in all xs by using x1 [5]+OT1,x1 [10]+OT1 and so on. For this purpose I have made this R code,

n=25

x1-runif(n,0,1)
x2-runif(n,0,1)
x3-runif(n,0,1)
x4-runif(n,0,1)
x-data.frame(x1,x2,x3,x4)

OT1-mean(x1)+100
OT2-mean(x2)+100
OT3-mean(x3)+100
OT4-mean(x4)+100

I have tried command replace() and also modify(), but none of them replace them at once at least in one vector. Kindly help me in this manner.

Edit

by using comment of @user2974951 I tried this

x1[seq(5,25,5)]=x1[seq(5,25,5)]+100
Nx1-replace(x1,x1==x1[5],x1 [5]+OT1)

x2[seq(5,25,5)]=x2[seq(5,25,5)]+100
Nx2-replace(x2,x2==x2[5],x1 [5]+OT2)

x3[seq(5,25,5)]=x3[seq(5,25,5)]+100
Nx3-replace(x3,x3==x3[5],x3 [5]+OT3)

x4[seq(5,25,5)]=x4[seq(5,25,5)]+100
Nx4-replace(x4,x4==x4[5],x4 [5]+OT4)
Nx-data.frame(Nx1,Nx2,Nx3,Nx4)

but its not working well

Results

         Nx1          Nx2         Nx3          Nx4
1    0.46815292   0.08606537   0.3307899 4.362630e-01
2    0.59723633   0.12122892   0.4819987 7.753236e-01
3    0.56219881   0.25936144   0.4990369 8.125097e-03
4    0.58366209   0.90552595   0.7368288 9.701722e-01
5  201.53593455 201.43976570 201.2130687 2.014071e+02
6    0.05521220   0.61975750   0.8296397 9.942981e-02
7    0.99058967   0.59373303   0.1156678 2.632295e-01
8    0.96428154   0.41710719   0.2547667 4.605275e-01
9    0.49978441   0.98922281   0.7526796 6.978671e-01
10 100.63831600 100.24166490 100.1790951 1.009707e+02
11   0.42694764   0.67506156   0.3142930 8.022078e-02
12   0.76015772   0.93265460   0.5734483 2.417875e-01
13   0.92832414   0.95247906   0.2578651 2.536677e-01
14   0.38818813   0.47634761   0.7163780 4.091937e-01
15 100.95118175 100.35951345 100.5519005 1.007286e+02
16   0.34262275   0.42573721   0.7594048 2.707246e-01
17   0.91930401   0.33828510   0.2679736 7.299545e-01
18   0.45901144   0.95876530   0.6419959 9.764771e-01
19   0.08840004   0.34092442   0.7492228 5.148988e-01
20 100.63958996 100.25792655 100.1351512 1.007377e+02
21   0.81191203   0.88845305   0.6504586 6.138992e-01
22   0.05737578   0.27700759   0.1193294 9.060633e-01
23   0.72447661   0.41372855   0.3055600 5.396204e-01
24   0.47942584   0.71890752   0.4814340 3.924752e-01
25 100.68191347 100.11710451 100.0443692 1.002326e+02

Why observation $5^{th}$ is 200+ and no outlier in $x4$???

Topic outlier statistics r

Category Data Science


You added 100 twice. And Nx4 is the same -- except that it's in scientific notations.

Nx1 = x1
Nx1[seq(5, 25, 5)] = mean(x1) + 100

will do.


You have a data frame with 4 columns, each columns has 25 rows. You want to replace every 5th element with an outlying value (the mean of the column).

apply(x,2,function(i){
    i[seq(5,25,5)]=i[seq(5,25,5)]+mean(i)
})

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.