AHF
AHF

Reputation: 1072

Working on vectors and finding their square

I am getting my self familiar with R, working on it using some mathematical work. I am working on indexing and seq function and getting help from here

I am first creating a vector x with all the integer from 1 to 200, I am performing this task using the code below

t <- 1:200

now I want to display the every 5th number using from above vector, I am doing it with below method

u <- seq (1,200, by=5)

First question: though the every 5th number is 5, 10 , 15 but its showing me 1, 6 , 11 etc

Now I want to take the square of any random numbers from vector t for that I am doing it in below way:\

square <-  t[c(4, 6, 7, 9, 16, 24, 26, 29,30)]^2 

Second question This is displaying me the square of these numbers but without using loops how I can display the numbers like 1,2,3,16,5,36 etc

I am using the below web pages for practice and understanding

https://rspatial.org/intr/4-indexing.html

https://www.r-exercises.com/start-here-to-learn-r/

Upvotes: 0

Views: 83

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102399

Another option is replace

t <- 1:200
v <- c(4, 6, 7, 9, 16, 24, 26, 29, 30)
replace(t, v, t[v]^2)

Upvotes: 1

akrun
akrun

Reputation: 887681

We can use an ifelse

ifelse(seq_along(t) %in% c(4, 6, 7, 9, 16, 24, 26, 29,30), t^2, t)

-output

[1]   1   2   3  16   5  36  49   8  81  10  11  12  13  14  15 256  17  18  19  20  21  22  23 576  25 676  27  28 841 900  31  32  33  34  35
 [36]  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70
 [71]  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105
[106] 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
[141] 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
[176] 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
 

Upvotes: 1

Related Questions