Write a for loop that replaces NAs with the mean of a given site across years.
Hint 1: Every row is a uniqe site. So the mean of the first site would be mean(penguins[1,]). However, can you use mean(penguins[1,]) if penguins is a data frame? How would you solve this issue?
Hint 2: Are NAs problematic when you use mean() directly? Look at the help file to solve this issue.
x, with all integers between 1 and 100.Create a for loop that computes x[i] * 2 for 100 iterations. Place the output in a list. However, break the loop after 51 iterations.
Create a for loop that computes x[i] * 2 for 100 iterations. Place the output in a vector. However, skip x = 71, 74.
Write a function that calculates the mean of every column in a dataframe. Code the function so that it evaluates the column mean if the column elements are numeric, using class(x) == “numeric”. Try your function on the iris dataset.
Write a function that checks every element in a matrix, and if an element is NA it changes it with a 0. Use a for loop in your function. Make sure your function is generalizable to matrices of any size, as long as nrow>1 and ncol>1. Check whether your function works as intended on the penguin data set and on a matrix you generated.
Create a list with following elements:
d = c(“x”, “y”, “z”)
Use lapply to calculate the standard deviation of each element of this list. Make sure the function you specify to lapply checks whether the element is numeric first, then calculates the standard deviation if it is numeric.