我正在使用dlply()和自定义函数,它平均lm()的斜率适合包含一些NA值的数据,我得到了错误 “lm.fit中的错误(x,y,offset = offset,singular.ok = singular.ok,...): 0(非NA)案例“
只有在用两个关键变量调用dlply时才会发生此错误 - 用一个变量分隔工作正常。
令人讨厌我无法使用简单的数据集重现错误,因此我已将问题数据集发布到我的保管箱中。
这是代码,尽可能减少,但仍会产生错误:
masterData <- read.csv("http://dl.dropbox.com/u/48901983/SOquestionData.csv", na.strings="#N/A")
workingData <- data.frame(sample = masterData$sample,
substrate = masterData$substrate,
el1 = masterData$elapsedHr1,
F1 = masterData$r1 - masterData$rK)
#This function is trivial as written; in reality it takes the average of many slopes
meanSlope <- function(df) {
lm1 <- lm(df$F1 ~ df$el1, na.action=na.omit) #changing to na.exclude doesn't help
slope1 <- lm1$coefficients[2]
meanSlope <- mean(c(slope1))
}
lsGOOD <- dlply(workingData, .(sample), meanSlope) #works fine
lsBAD <- dlply(workingData, .(sample, substrate), meanSlope) #throws error
提前感谢任何见解。
答案 0 :(得分:5)
对于您的几个交叉分类,您缺少协变量:
with(masterData, table(sample, substrate, r1mis = is.na(r1) ) )
#
snipped the nonmissing reports
, , r1mis = TRUE
substrate
sample 1 2 3 4 5 6 7 8
3 0 0 0 0 0 0 0 0
4 0 0 0 0 0 0 0 0
5 0 0 0 0 0 0 0 0
6 0 0 0 0 0 0 0 0
7 0 0 0 0 0 0 3 3
8 0 0 0 0 0 0 0 3
9 0 0 0 0 0 0 0 3
10 0 0 0 0 0 0 0 3
11 0 0 0 0 0 0 0 3
12 0 0 0 0 0 0 0 3
13 0 0 0 0 0 0 0 3
14 0 0 0 0 0 0 0 3
这可以让你跳过这个特定数据中数据不足的子集:
meanSlope <- function(df) { if ( sum(!is.na(df$el1)) < 2 ) { return(NA) } else {
lm1 <- lm(df$F1 ~ df$el1, na.action=na.omit) #changing to na.exclude doesn't help
slope1 <- lm1$coefficients[2]
meanSlope <- mean(c(slope1)) }
}
虽然这取决于某个特定协变量的缺失。更强大的解决方案是使用try
来捕获错误并转换为NA。
?try
答案 1 :(得分:2)
根据我的评论:
my.func <- function(df) {
data.frame(el1=all(is.na(df$el1)), F1=all(is.na(df$F1)))
}
ddply(workingData, .(sample, substrate), my.func)
显示您有许多子集,其中F1和el1都是NA。 (事实上每次一个人都是na,另一个人也是!)