# Define ratio() function
ratio <- function(x, y) {
x/y
}
# Cal ratio() with arguments 3 and 4
ratio(3,4)
Scoping Summary
● When you call a function, a new environment is made for the function to do its work
● The new environment is populated with the argument values
● Objects are looked for first in this environment
● If they are not found, they are looked for in the environment that the function was created in.
That is, my_list[[1]] extracts the first element of the list my_list, and my_list [["name"]] extracts the element in my_list that is called name. If the list is nested you can travel down the heirarchy by recursive subsetting. For example, my_list[[1]][["name"]] is the element callednameinside the first element of my_list.
# 2nd element in tricky_list
typeof(tricky_list[[2]])
# Element called x in tricky_list
typeof(tricky_list[["x"]])
# 2nd element inside the element called x in tricky_list
typeof(tricky_list[["x"]][[2]])
# Replace the 1:ncol(df) sequence
for (i in seq_along(df)) {
print(median(df[[i]]))
}
# Change the value of df
df <- data.frame()
# Repeat for loop to verify there is no error
for (i in seq_along(df)) {
print(median(df[[i]]))
}
# Create new double vector: output
output<-vector("double",ncol(df))
# Alter the loop
for (i in seq_along(df)) {
# Change code to store result in output
output[[i]]<-median(df[[i]])
}
# Print output
output
网友评论