r - 在循环 (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)
}
解决方案
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
数据框。
推荐阅读
- sql - 删除所有不喜欢所需值的字符
- javascript - 以 GZIP/ZIP 格式对 XML 的 AJAX 请求 - 如何在 Javascript 中解压缩数据
- c# - 更改为 64 位后用户范围的设置丢失
- python - 无法使用python在redis中使用ZADD(排序集)插入数据
- php - Xampp Mysql 未运行 MySQL 意外关闭
- json - micropython 中的 json 帖子
- jquery - Jquery tokenInput - 无法读取未定义问题的属性
- javascript - d3 xScale 坏了
- bluetooth-lowenergy - BLE 5 的 PCB 轨道天线或 SMD 芯片天线?
- html - 无法在 iOS 上的 Bootstrap 模式中滚动 iframe