A quick refresher

# 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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容