一层循环: data1<-matrix(c(1:15),nrow = 5, ncol=3, byrow=TRUE) data1 sum_my<-function(x){ sum(x) } col.sums <- apply(data1, 2, sum_my)
col.sums row.sums <- apply(data1, 1, sum_my)
row.sums # sum_my can be changed into any function using column or row as input
########### For example ### correlation with a vector data1<-matrix(c(1:15),nrow = 5, ncol=3, byrow=TRUE) data1 data_4cor <- c(1,3,2) sum_cor<-function(x){ cor(x,data_4cor) }
二层循环: (数据框) data2<-as.data.frame(data1) x <- data2 y <- data2 bl <- lapply(x, function(u){ lapply(y, function(v){ # function(u,v) # Function with column from x and column from y as inputs cor(u,v) # As an example }) }) out = matrix(unlist(bl), ncol=ncol(y), byrow=T) out
(向量) data3<- c(1:9) x <- data3 y <- data3 bl <- lapply(x, function(u){ lapply(y, function(v){ sum(u,v) # Function with each data from x and column from y as inputs }) }) out = matrix(unlist(bl), ncol=length(y), byrow=T) out