Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore code when data does not contain necessary values?

Tags:

r

na

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

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 .

like image 961
Gladdys Gotherin Avatar asked Aug 13 '26 04:08

Gladdys Gotherin


1 Answers

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:

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.

like image 150
flodel Avatar answered Aug 16 '26 08:08

flodel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!