-1

For instance, I have a vector like this

x <- c(NA, NA, NA, 12, NA)

I want R to print the first non-NA element (12) without using which or downloading packages. I guess I should make a condition that is.na(x) = FALSE but I don't know how.

Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32
Kristina
  • 1
  • 1
  • 1
    It would help to know *why* you want to avoid `which`. – Konrad Rudolph Oct 06 '21 at 10:19
  • 4
    Everything in R is a function (or a data structure). You can't use R without built-in functions. – Roland Oct 06 '21 at 10:20
  • 2
    I guess this is a homework, and by built-in they meant to avoid functions like "which", "na.omit" etc. Maybe using "forloop check if it is na, then print" is the solution. – zx8754 Oct 06 '21 at 10:23

1 Answers1

3

Here are couple of ways -

#1.
na.omit(x)[1]
#[1] 12

#2.
x[!is.na(x)][1]
#[1] 12
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks for posting the answers Ronak. Even tho this looks like a 'do my homework' question, it's still handy for those of us using stackoverflow-search as a quick reference. – David T Feb 09 '23 at 15:46