2
v1 = c(1,2,3)
v2 = c("a","b",NA)
X = data.frame(v1,v2)

f = function(X,d){
    subset(X,is.na(d)==0)
    }
f(X,"v2")

How can I get the subset of X for which any given column (inputted into the argument of a function) isn't missing?

3 Answers 3

5

Note: The function subset should not be used in functions but interactively only (see here).

f <- function(X, d) {
  X[!is.na(X[d]), ]
}

> f(X,"v2")
  v1 v2
1  1  a
2  2  b
Sign up to request clarification or add additional context in comments.

Comments

3

If you use complete.cases you can input a vector of column names.

f <- function(X,d) {
     X[complete.cases(X[,d]),]
 }

Comments

1

You don't need a function. Just do:

X[!is.na(X$v2),]

2 Comments

True, but my interpretation of the OP's question was how to write this sort of function in the general case, where rewriting the arguments to the [ operator might not be so simple.
Yes, after I posted I wondered if the question was about genuinely needing a function or just not knowing how to subset without subset. Others have since provided answers to the former, however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.