ljxue的个人博客分享 http://blog.sciencenet.cn/u/ljxue Liangjiao Xue, Bioinformatics is my favorite.

博文

R的隐式循环

已有 3950 次阅读 2012-6-26 02:18 |系统分类:科研笔记| 循环

一层循环:
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)
}

row.cor <- apply(data1, 1, sum_cor)
row.cor
##########


二层循环:
(数据框)
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




https://blog.sciencenet.cn/blog-285393-585860.html

上一篇:R & Bioconductor Manual
下一篇:Online Plant Comparative Genomics Tools
收藏 IP: 128.192.8.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-11-15 16:22

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部