首页 > 解决方案 > R - 试图从数据表中矢量化 colnames 选择

问题描述

我正在尝试对我的代码进行矢量化以使其更具重现性!

当这些列之一小于 5 时,我想在我的 R Markdown 报告中打印一条警告消息!这是我在矢量化之前的第一个代码:

JO_ratio_JOUR <- JO_ratio_tranches[dir == "ALLER" & (.1_JO[4h_7h[_txcouv < 5 | .2_JO[7h_9h[_txcouv < 5 | .3_JO[9h_12h[_txcouv < 5 | .4_JO[12h_15h30[_txcouv < 5 | .5_JO[15h30_18h[_txcouv < 5 | 6_JO[18h_20h[_txcouv < 5 | .7_JO[20h_22h[_txcouv < 5 | .8_JO[22h_4h[_txcouv < 5), grep("txcouv", names(JO_ratio_tranches))]
if(!is_empty(JO_ratio_JOUR)){print(" WARNING: Ratio < 5% !")}

[1] "WARNING: Ratio(s) < 5% !"

好的 !

但是,当我尝试通过 for 循环将此代码向量化时,R 每次在表中找到小于 5% 的值时都会打印警告消息!:(

JO_ratio_JOUR <- JO_ratio_tranches[dir == "ALLER", ]
for(i in grep("txcouv", names(JO_ratio_JOUR))){
  if(JO_ratio_JOUR[[i]] < 5){print(" WARNING: Ratio < 5% !")}

[1] "WARNING: Ratio(s) < 5% !"
[1] "WARNING: Ratio(s) < 5% !"
[1] "WARNING: Ratio(s) < 5% !"
[1] "WARNING: Ratio(s) < 5% !"

咳!!!!

如果这些列中的任何一个小于 5 ,我如何只打印一条警告消息?

非常感谢你的帮助 !

标签: rfor-loopvectorization

解决方案


推荐阅读