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

do.call()的具体用法?

posted @ 2017-07-16 23:05  银河统计  阅读(3196)  评论(0编辑  收藏  举报