In: Computer Science
Use R code to do the following!!!!
1. Create a vector v1 that will contain integers from -30 to
60.
2. Copy v1 into a vector v2 and add names 'odd' or 'even' based on
the value.
3. Copy v1 into a vector v3 and if the number can be divided by 3,
replace it by 'NA'.
4. Assign the mean of v3 to v4 ignoring the 'NA'.
Screenshot
Program
#1. Create a vector v1 that will contain integers from -30 to
60.
v1 <- -30:60;
#2. Copy v1 into a vector v2 and add names 'odd' or 'even' based on
the value.
v2=vector();
for(i in 1:length(v1)){
if(v1[i]%%2==0){
v2[i]='even';
}
else{
v2[i]='odd';
}
}
#Copy v1 into a vector v3 and if the number can be divided by 3,
replace it by 'NA'.
v3=vector();
for(i in 1:length(v1)){
if(v1[i]%%3==0){
v3[i]=NA;
}
else{
v3[i]=v1[i];
}
}
#Assign the mean of v3 to v4 ignoring the 'NA'.
v4=mean(v3,trim=0,na.rm=TRUE);
#Display all
cat("Values of v1 vector:-\n")
print(v1)
cat("\nValues of v2 vector:-\n")
print(v2)
cat("\nValues of v3 vector:-\n")
print(v3)
cat("\nValues of mean in v4:-\n")
print(v4)
------------------------------------------------------
Output
Values of v1 vector:-
[1] -30 -29 -28 -27 -26 -25 -24 -23 -22 -21 -20 -19 -18 -17 -16 -15
-14 -13 -12
[20] -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
1 2 3 4
5 6 7
[39] 8 9 10 11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26
[58] 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
[77] 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
Values of v2 vector:-
[1] "even" "odd" "even" "odd" "even" "odd" "even" "odd" "even"
"odd"
[11] "even" "odd" "even" "odd" "even" "odd" "even" "odd" "even"
"odd"
[21] "even" "odd" "even" "odd" "even" "odd" "even" "odd" "even"
"odd"
[31] "even" "odd" "even" "odd" "even" "odd" "even" "odd" "even"
"odd"
[41] "even" "odd" "even" "odd" "even" "odd" "even" "odd" "even"
"odd"
[51] "even" "odd" "even" "odd" "even" "odd" "even" "odd" "even"
"odd"
[61] "even" "odd" "even" "odd" "even" "odd" "even" "odd" "even"
"odd"
[71] "even" "odd" "even" "odd" "even" "odd" "even" "odd" "even"
"odd"
[81] "even" "odd" "even" "odd" "even" "odd" "even" "odd" "even"
"odd"
[91] "even"
Values of v3 vector:-
[1] NA -29 -28 NA -26 -25 NA -23 -22 NA -20 -19 NA -17 -16 NA -14
-13 NA
[20] -11 -10 NA -8 -7 NA -5 -4 NA -2 -1 NA
1 2 NA 4 5 NA
7
[39] 8 NA 10 11 NA 13 14 NA 16 17 NA 19 20 NA 22 23 NA
25 26
[58] NA 28 29 NA 31 32 NA 34 35 NA 37 38 NA 40 41 NA 43 44 NA
[77] 46 47 NA 49 50 NA 52 53 NA 55 56 NA 58 59 NA
Values of mean in v4:-
[1] 15