【问题标题】:Apply a condition to a for loop to plot over all dataframes R将条件应用于 for 循环以绘制所有数据帧 R
【发布时间】:2015-11-14 11:35:59
【问题描述】:

我正在尝试根据多个数据帧中某个因子的值有条件地输出绘图。我的数据帧是“n310”和 323 个附加数据帧“mrns[[i]]”。

我为 n310 数据框中的变量创建了类别:

n310$ar.cat[n310$arousals_index_per_h_sleep <= 14.9 & n310$arousals_index_per_h_sleep != "NA"] <- "LOW"
n310$ar.cat[n310$arousals_index_per_h_sleep > 14.9 & n310$arousals_index_per_h_sleep < 29.4] <- "MED"
n310$ar.cat[n310$arousals_index_per_h_sleep >= 29.4] <- "HIGH"

我通过匹配各自的mrn变量,将n310的分类变量和连续变量添加到mrns[[i]]中:

for (i in 1:323) {
  mrns[[i]]$ar.value <- n310$arousals_index_per_h_sleep[match(mrns[[i]]$raw.mrn, n310$mrn)]
  mrns[[i]]$ar.cat <- n310$ar.cat[match(mrns[[i]]$raw.mrn, n310$mrn)]
}

然后我尝试仅绘制 mrns[[i]]$ar.cat 的“LOW”类别:

for (i in 1:323) {
  if (mrns[[i]]$ar.cat == "LOW") {
    png(paste0(arIndLowSys, mrns[[i]]$raw.mrn, "_systolic_ar_index_low.png"), height=1600, width=1600, res=200, family="Times")
    plot(mrns[[i]]$raw.Hour, mrns[[i]]$raw.Systolic, main="Systolic Blood Pressure per Hour of Day", xlab="Hour of Day", ylab="Systolic Blood Pressure", family="Times", bty="L", xlim=c(0, 24), xaxp=c(0, 24, 12))
    mtext(mrns[[i]]$ar.value, side=4, line=0)
    mtext(mrns[[i]]$ar.cat, side=4, line=-1)
    dev.off()
}}

并得到以下错误:

Error in if (mrns[[i]]$ar.cat == "LOW") { : 
  missing value where TRUE/FALSE needed

mrns[[i]]$ar.cat 有“NA”或缺失值,所以我不是在制作绘图时如何忽略这些“NA”值。

大家有什么建议吗?

谢谢!

【问题讨论】:

  • 如果您的 324 个数据集不是非常大,不要让您的生活变得困难,而不是将每个数据集作为列表元素创建一个包含所有数据集的大数据集并创建一个“数据集 id”列。您可以按此 id 分组并将相同的过程应用于每个数据集。

标签: r if-statement for-loop plot conditional-statements


【解决方案1】:

if (!is.na(mrns[[i]]$ar.cat)) 包裹在您的代码周围,以便仅绘制不等于NA 的索引。

for (i in 1:323) {
  if (!is.na(mrns[[i]]$ar.cat)) {
        if (mrns[[i]]$ar.cat == "LOW") {
            png(paste0(arIndLowSys, mrns[[i]]$raw.mrn, "_systolic_ar_index_low.png"), height=1600, width=1600, res=200, family="Times")
            plot(mrns[[i]]$raw.Hour, mrns[[i]]$raw.Systolic, main="Systolic Blood Pressure per Hour of Day", xlab="Hour of Day", ylab="Systolic Blood Pressure", family="Times", bty="L", xlim=c(0, 24), xaxp=c(0, 24, 12))
            mtext(mrns[[i]]$ar.value, side=4, line=0)
            mtext(mrns[[i]]$ar.cat, side=4, line=-1)
            dev.off()
        }
  }
}

【讨论】:

    【解决方案2】:

    按照您编写问题的方式假设,您的数据框在列表中...

    你需要使用你的逻辑语句作为索引:

    ind = sapply(mrns, function(i){
        which(i$ar.cat == "LOW")
    }
    
    for (i in ind) {
        # Your code
    }
    

    未经测试,但你明白了......

    作为比较,以下是 lapply 的外观:

    lapply(ind, function(i){
        # Your code
    })
    

    【讨论】:

    • 感谢@MikeRSpencer!数据框在列表中。我只是试图索引代码(带有一个额外的右括号),我得到了错误“mrns [[i]] 中的错误:无效的下标类型'list'”。
    • 糟糕!修正了错误。我认为 sapply 将在列表中运行,如果不是,则需要进行一些编辑。
    • 上面给出了解决方案,感谢您的时间@Mike!
    • 不用担心。看到不同的做事方式总是很高兴。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 2017-07-21
    • 2021-11-23
    • 2016-01-31
    相关资源
    最近更新 更多