3

我对 R 和这里也很陌生,需要一些帮助来修复我的代码,因为有时我的数据会变得很奇怪

所以我有类似的数据

Random  Price
11.23   0.68
66.77   0.51
68  0.46
78  0.51
88  0.32
89  0.51
90  0.27
91  0.65

到目前为止,这是我的代码:

newdata <- data[ which(data$Random>=30
& data$Random < 50), ]
Pvalue<- lapply(1:length(dat), function(i){
if(length(dat[[i]][[4]])>1){
t.test(newdata$Price,dat[[i]][[4]])$p.value 
}else 'not enough observation'
})

'newdata'我的代码基本上在数据和另一组数据之间进行了 t.test,'dat' 但有时我没有data与上面的示例数据类似的 30 到 50。因此,我的代码不是返回错误,而是如何更改它以使其仅返回NA.

4

1 回答 1

3

您已经知道如何使用该if/else构造。您所要做的就是添加一项测试nrow(newdata),或者将两者结合起来,如下所示:

newdata <- subset(data, Random >= 30 &
                        Random < 50)
Pvalue <- lapply(dat, function(x){
  if (length(x[[4]]) > 1 & nrow(newdata) > 1) {
    t.test(newdata$Price, x[[4]])$p.value 
  } else NA
})

You could also replace lapply(...) with sapply(...) or vapply(..., numeric(1)) to get a numeric vector instead of a list. For that, it is recommended to replace 'not enough observation' with NA like I did, or you could end up with a character vector.

于 2013-03-30T13:00:14.780 回答