how to use min() and if()else without full data

hello,

I am thinking about solution to following problem:

A = 5
B = 6
C = ...... (lack of data because of past error - the C value wasn't generated)
D = 3

min.v <- min(A,B,C,D)
if(min.v = A) parameterA else
if(min.v = B) parameterB else
if(min.v = C) parameterC else parameterD

in this situation min() an if()else generate an error because there is no C value. How can I handle with it? First of all, I want to take the minimum value just for available set (A,B,C,D) elements and of course I don;t know which elements will be available and which not. Next, I would like to use if()else condition (which, like I think, also will not work properly in the conditions of missing elements..)

Or maybe there is some function similar to iferror, which could replace C value to different, my own value, when there is an error?

Hi,

It's quite an easy fix, you can just remove the NA values during the operations of min/max/mean/...

myList = c(3:5, NA, 6:10)
cleanList = myList[!is.na(myList)]

min(cleanList)
[1] 3

By the way, you can also filter in data frames:

myData = data.frame(x = 1:10, 
                    y = c(1, NA, 3:5, NA, 7:10),
                    z = c(1:5, NA, 7, 8, NA, 10))
    x  y  z
1   1  1  1
2   2 NA  2
3   3  3  3
4   4  4  4
5   5  5  5
6   6 NA NA
7   7  7  7
8   8  8  8
9   9  9 NA
10 10 10 10

#Filter a particular column in data frame
myData[!is.na(myData$y),]
    x  y  z
1   1  1  1
3   3  3  3
4   4  4  4
5   5  5  5
7   7  7  7
8   8  8  8
9   9  9 NA
10 10 10 10

#Filter all columns in a data frame
myData[complete.cases(myData),]
    x  y  z
1   1  1  1
3   3  3  3
4   4  4  4
5   5  5  5
7   7  7  7
8   8  8  8
10 10 10 10

Hope this helps,
PJ

2 Likes

Handling missing values isn't too hard in R. You just need to remember what they represent: unknown data. If you have a collection with an unknown value, you can't know which of the values is smallest. To ignore missing values, you have to explicitly write the code. This lets you, R, and anyone reading your code know what the code assumes.

A lot of functions, including min(), come with an na.rm = TRUE argument.

vals <- c(A = 5, B = 6, C = NA, D = 3)
vals
#  A  B  C  D 
#  5  6 NA  3 
min(vals, na.rm = TRUE)
# [1] 3

Also, I'd recommend using which.min for your code. It returns which element in a vector is the smallest value. It always ignores missing values.

pars <- c("parameterA", "parameterB", "parameterC", "parameterD")
pars[which.min(vals)]
# [1] "parameterD"
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.