【发布时间】: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