初识R语言之条件循环篇

初识R语言之条件循环篇,第1张

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

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

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
}

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

每文一语

累了,该休息了

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5075063.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存