for
Loopsfor
LoopsNested for
Loops
More Examples
for
LoopsNested for
loops are for
loops within another for
loop. You can stack these loops as much as needed. Just make sure the index is different for each loop. The general format for a loop goes as follow:
Without using the sd()
function, compute the standard deviation for each column of the matrix:
\[ s^2 = \frac{1}{n-1}\sum^n_{i=1}(x_i-\bar x)^2 \]
Nested for
Loops
More Examples
The median()
function obtain the median value of a vector. Write code to obtain the median value for any vector.
Answer:
wk <- x
pos50 <- (length(wk) + 1) / 2
swk <- sort(wk)
if ((length(wk) %% 2) == 0) {
val <- (swk[floor(pos50)] + swk[ceiling(pos50)]) / 2
} else {
val <- swk[pos50]
}
print(val)
median(wk)
wk <- y
pos50 <- (length(wk) + 1) / 2
swk <- sort(wk)
if ((length(wk) %% 2) == 0) {
val <- (swk[floor(pos50)] + swk[ceiling(pos50)]) / 2
} else {
val <- swk[pos50]
}
print(val)
median(wk)
Using the code below:
Create a new vector containing all the positive values of x
. The new vector should be less than 5000.
Answer:
Create a vector reporting the data type of each variable in ISLR2::BrainCancer
Answer:
\[ f(x,y) = x^2 + y^2 + \ln(x+y) \]
Find all the values of \(f(x,y)\) for every combination of \(x \in \{1, 8, 13, 25, 42, 67, 95\}\) and \(y \in \{6, 12, 18, 52, 61, 79, 83\}\)
Store values in a \(7\times 7\) matrix.
Answer:
For each column in mtcars
, take the mean for the even columns, and median for the odd columns. Store the values in a list containing 2 vectors.
Answer: