初识R语言之条件循环篇

简介: 初识R语言之条件循环篇
pool = 1:10
for(fish in pool){
  print(fish)
}

image.png

通过循环操作读取文件并进行数据的处理

files = c('DEG1.xls', 'DEG2.xls', 'DEG3.xls', 'DEG4.xls')
n = 1
for(file in files){
  print(paste0('DEG unfiltered file is ', file))
  # 1 reading DEG unfiltered file
  df = read.delim(file, header = T, sep = '\t')
  # 2 filtering different expressed genes
  df$logFC = log2(df$FC)
  deg = subset(df, abs(logFC) > 1 & pval < 0.05)
  # 3 reading TF annotation file
  TF = read.delim('Homo_sapiens_TF.txt', header = T, sep = '\t')
  # 4 annotate DEGs with TF family information
  deg_TF_all = merge(deg, TF, 
                     by.x = 'id', 
                     by.y = 'Symbol',
                     all.x = T)  
  # 5 output annotated DEGs
  outfile_name = paste0('deg_TF_', n, '.xls')
  write.table(deg_TF_all, outfile_name,
              col.names = T, row.names = F,
              sep = '\t', quote = F)
  n = n + 1
}

判断

a = 2
b = 3
c = 1
if(a > b){
  print('a > b')
}
if(a > b){
  print('a > b')
} else {
  print('a <= b')
}
if(a > b){
  print('a > b')
} else if(a > c){
  print('a > c')
} else {
  print('a <= b and a <= c')
}

基本语法和java与C语言有点类似,思想和Python相符合

批量处理4个文件:差异筛选+TF注释

如果已经加载TF数据库,则不再读取

files = c('DEG1.xls', 'DEG2.xls', 'DEG3.xls', 'DEG4.xls')
n = 1
for(file in files){
  print(paste0('Processing file is ', file))
  # 1 reading DEG unfiltered file 
  df = read.delim(file, header = T, sep = '\t')
  # 2 filtering different expressed genes
  df$logFC = log2(df$FC)
  deg = subset(df, abs(logFC) > 1 & pval < 0.05)
  if(exists('TF')){
    print('TF database has already existed')
  } else {
    # 3 reading TF annotation file 
    TF = read.delim('Homo_sapiens_TF.txt', header = T, sep = '\t')
  }
  # 4 annotate DEGs with TF family information
  deg_TF_all = merge(deg, TF, 
                     by.x = 'id', 
                     by.y = 'Symbol',
                     all.x = T)  
  # 5 output annotated DEGs 
  outfile_name = paste0('deg_TF_', n, '.xls')
  write.table(deg_TF_all, outfile_name,
              col.names = T, row.names = F,
              sep = '\t', quote = F)
  n = n + 1
}

对于基本的循环判断其实和其他的编译语言差不多

相关文章
R语言笔记丨三大法宝:判断、循环、函数
R语言笔记丨三大法宝:判断、循环、函数
R语言 循环作图
setwd("C:\\Users\\Administrator\\Desktop\\pic") # Plot separate ggplot figures in a loop.
1306 0
|
人工智能
R语言for循环①
for循环是一种重复控制结构,可以让您有效地编写一个需要执行特定次数的循环。 for (value in vector) { statements } 示例: j a for (i in c(1:length(a))) + {pr...
1142 0
|
存储
《R语言编程艺术》——2.3 循环补齐
本节书摘来自华章计算机《R语言编程艺术》一书中的第2章,第2.3节,作者:(美)麦特洛夫(Matloff,N.)著, 更多章节内容可以访问云栖社区“华章计算机”公众号查看。
1727 0
R语言的循环
R语言的for循环支持任何向量(注意,是向量),无论向量是任何模式,如 x
963 0