R语言-do.call用法小结
?do.call
do.call(what, args, quote = FALSE, envir = parent.frame())
Examples1
do.call("complex", list(imag = 1:3))
## if we already have a list (e.g., a data frame)
## we need c() to add further arguments
tmp <- expand.grid(letters[1:2], 1:3, c("+", "-"))
do.call("paste", c(tmp, sep = ""))
do.call(paste, list(as.name("A"), as.name("B")), quote = TRUE)
## examples of where objects will be found.
A <- 2
f <- function(x) print(x^2)
env <- new.env()
assign("A", 10, envir = env)
assign("f", f, envir = env)
f <- function(x) print(x)
f(A) # 2
do.call("f", list(A)) # 2
do.call("f", list(A), envir = env) # 4
do.call(f, list(A), envir = env) # 2
do.call("f", list(quote(A)), envir = env) # 100
do.call(f, list(quote(A)), envir = env) # 10
do.call("f", list(as.name("A")), envir = env) # 100
eval(call("f", A)) # 2
eval(call("f", quote(A))) # 2
eval(call("f", A), envir = env) # 4
eval(call("f", quote(A)), envir = env) # 100
Examples2
有一个list,想把里面的所有元素相加求和,发现了两个很有意思的函数。
list <- list(matrix(1:25, ncol = 5), matrix(4:28, ncol = 5), matrix(21:45, ncol=5))
list.sum <- do.call(sum,list)
list.sum <- do.call(cbind,list)
list.sum <- do.call(rbind,list)
do.call()是告诉list一个函数,然后list里的所有元素来执行这个函数。
Examples3
# oPath <- "C:/Users/abdata/Desktop/"
# oName <- "test_data"
# oType <- "csv"
# oPathFile <- paste(oPath,oName,'.',oType,sep="",collapse="")
# test_data <- read.csv(oPathFile,header=T)
test_data <- read.csv('http://data.galaxystatistics.com/blog_data/test_data_do_call.csv',header=T)
# class(test_data)
id_x <- paste0(test_data$USER_ID, test_data$TOPIC_NO, sep="")
test_data <- data.frame(test_data, id_x)
data <- split(test_data, test_data$id_x)
data1 <- lapply(data, function(data){
index <- order(data[,5])
data_top <- head(data[index, ],6)
USER_ID <- data_top[1,2]
TOPIC_NO <- data_top[1,3]
TOPIC_NAME <- paste(data_top[,4], collapse=" ")
result <- data.frame(USER_ID, TOPIC_NO, TOPIC_NAME)
})
# class(do.call(rbind,data1))
result <- do.call(rbind,data1)
result
# or test
DM <- data.frame()
for (i in 1:length(data1)){
DM <- rbind(DM, data1[[i]])
}
result <- DM[,-ncol(DM)]
result
Examples4
©哈尔滨商业大学 银河统计工作室
银河统计工作室成员由在校统计、计算机部分师生和企业数据数据分析师组成,维护和开发银河统计网和银河统计博客(技术文档)。专注于数据挖掘技术研究和运用,探索统计学、应用数学和IT技术有机结合,尝试大数据条件下新型统计学教学模式。
邮箱:wanglei@hrbcu.edu.cn 关于我们