首页 > 解决方案 > 在循环 (for) 中使用 if & else if 语句进行条件格式

问题描述

我有一个包含 52 列、1290 行的矩阵,其中包含我已成功运行的循环的 p 值和系数。

在这种情况下,我想根据相关的 p 值(第 19 列),通过在系数值的末尾附加星号来有条件地格式化变量的系数 (r) 值(第 3 列)。

当存在指数 p 值时,我无法成功追加"***",我也尝试过设置options(scipen=999)但无济于事。我已经能够使用str_sub()and隔离 p 值中存在的“e” stri_sub(),因此如果我可以让 ifs 在循环中正常工作,我可以使用 if 语句:

# p<0.001 (append "***") # p<0.01 (append "**") # p<0.05 (append "*")

以下语句单独工作正常,但当我将以下内容添加到for()循环中时失败:

# Working asterisk append to coefficient value 
if(as.numeric(cell_id_input) < 0.05) {
cell_id_out <- paste0(cell_id_out,"*", sep="")     
}

使用指定的列(仅限 3 和 19)遍历矩阵“dta”中的每一行,如果满足以下条件,则附加星号:

for (j in 1:nrow(dta)){
  cell_id_input <- dta[j,19] # Column that contains associated (p) values for 'cell_id_out'
  cell_id_out <- dta[j,3] { # Column that contains the coefficient (r) value associated with 'cell_id_input' 
  if(as.numeric(cell_id_input) < 0.001) { 
    cell_id_out <- paste0(cell_id_out,"***", sep="") 
} else if (as.numeric(cell_id_input) < 0.01) {
    cell_id_out <- paste0(cell_id_out,"**", sep="") 
} else if(as.numeric(cell_id_input) < 0.05) {
    cell_id_out <- paste0(cell_id_out,"*", sep="") 
} else {
    cell_id_out <- paste(cell_id_out)
}

标签: r

解决方案


df=data.frame("a"=c(0.1,0.6,0.00000000001,0.000000002),
           "b"=c(1,4,3,5),stringsAsFactors = FALSE)
df$a = as.character(df$a)
for (i in 1:nrow(df)){
  if (as.numeric(df$a[i])<0.05){
    df$a[i]=paste0(df$a[i],"*")
  }
}
       a b
1    0.1 1
2    0.6 4
3 1e-11* 3
4 2e-09* 5

这对我有用。您可以根据自己的情况对其进行调整。您的问题是您将结果分配给cell_id_out变量,而不是dta数据框。


推荐阅读