当数据不包含必要的值时,如何忽略代码?

时间:2021-07-19 15:36:44

I'm very new to R and here as well and need some help fixing my code because sometimes my data gets weird

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

So I have data similar to this

我有类似的数据

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

This is my code so far:

这是我目前的代码:

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'
})

My code basically does a t.test between the data from 'newdata' and another set of data called 'dat' But there are times when I don't have data from 30 to 50 similar to my example data above. So instead of my code returning an error, how could I change it so that it just returns NA .

我的代码基本上是t。在来自“newdata”的数据和另一组名为“dat”的数据之间进行测试,但有时我没有类似于上面示例数据的30到50的数据。我的代码不会返回一个错误,我怎么能改变它,让它返回NA。

1 个解决方案

#1


3  

You already know how to use the if/else construct. All you have to do is add one testing nrow(newdata), or maybe combine both as follows:

您已经知道如何使用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.

您还可以用sapply(…)或vapply(…)替换lapply(…),以获得一个数值向量而不是一个列表。为此,建议像我一样用NA代替“观察不足”,或者您可以使用字符向量。

#1


3  

You already know how to use the if/else construct. All you have to do is add one testing nrow(newdata), or maybe combine both as follows:

您已经知道如何使用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.

您还可以用sapply(…)或vapply(…)替换lapply(…),以获得一个数值向量而不是一个列表。为此,建议像我一样用NA代替“观察不足”,或者您可以使用字符向量。