1. args 函数
Argument List of a Function
args(mean)
查看 mean()
函数的参数设置要求。
2. 函数内的变量
Variables that are defined inside a function are not accessible outside that function.
函数里面定义的变量在函数外面无法调用。
R function cannot change the variable that you input to that function.
函数不能改变函数外面已有变量的值。
3. 自编函数
背景:logs
是一个list,里面的每一个元素也是list。见下面。
List of 96
$ :List of 3
..$ success : logi TRUE
..$ details :List of 1
.. ..$ message: chr "check"
..$ timestamp: POSIXct[1:1], format: "2015-09-14 23:01:07"
$ :List of 3
..$ success : logi TRUE
..$ details :List of 1
.. ..$ message: chr "all good"
..$ timestamp: POSIXct[1:1], format: "2015-09-15 00:00:13"
$ :List of 3
..$ success : logi TRUE
..$ details :List of 1
.. ..$ message: chr "check"
..$ timestamp: POSIXct[1:1], format: "2015-09-15 01:00:43"
任务:提取任何一个 list 里面的任何一个 property
# 1. 自编函数
extract_info <- function(x, property) {
info <- c()
for (log in x) {
info <- c(info, log[[property]])
}
return(info)
}
# 2. 调用函数
# Call extract_info() on logs, set property to "timestamp"
extract_info(logs, "timestamp")
# Call extract_info() on logs, set property to "success"
extract_info(logs, "success")
特别需要注意的点1:
如果不写在函数体里面,单纯的想要提取logs 这个list 里面的内容,可以使用 $ 符号,例如:
> logs[[1]]$timestamp
[1] "2015-09-14 23:01:07 UTC"
如果写在函数体里面,不能使用 $ 符号,必须使用 [[]]。上文的命令中 for循环内部的语句不能写成:
info <- c(info, log$property)
解释:You cannot use the $ notation if the element you want to select is a variable and not the actual name of a list。
如果你想要选择的元素是一个变量,而不是列表的名称,那么不能使用 $ 符号。
特别需要注意的点2:
函数调用时,第二个参数要加双引号。
extract_info(logs, "timestamp")
4. 自编函数复杂化的过程
代码来源:datacamp 课程
intermediate-r-practice
# 1. for loop, extract "timestamp" information in "logs" list.
info <- c()
for (log in logs) {
info <- c(info, log$timestamp)
}
# 2. step 1 function, substitute for "list"
extract_info <- function(x) {
info <- c()
for (log in x) {
info <- c(info, log$timestamp)
}
return(info)
}
extract_info(logs)
# 3. step 2 function, substitute for "list" and "property"
extract_info <- function(x, property) {
info <- c()
for (log in x) {
info <- c(info, log[[property]])
}
return(info)
}
extract_info(logs, "timestamp")
# 4. step 3 funtion, set a default "property" value
extract_info <- function(x, property = "success") {
info <- c()
for (log in x) {
info <- c(info, log[[property]])
}
return(info)
}
extract_info(logs)
extract_info(logs, property = "timestamp")
# 5. step 4 function, select part of list
extract_info <- function(x, property = "success", include_all = TRUE) {
info <- c()
for (log in x) {
if (include_all || !log$success){
info <- c(info, log[[property]])
}
}
return(info)
}
extract_info(logs) # select all list elements' "success"
extract_info(logs, include_all = FALSE) # select list elements which "success" is false
# 6. step 5 function, select a nested list elements
extract_info(logs, property = c("details", "message"))