MarioHo
MarioHo

Reputation: 31

Select the first 2 NA values of each row in a dataframe

Given a dataframe like this:

           A         B         C         D         E
1         NA 0.1189026 0.1189026        NA        NA
2         NA 0.1189026 0.1189026        NA        NA
3         NA        NA        NA        NA        NA
4         NA        NA        NA        NA        NA
5  0.3214921        NA        NA 0.3214921 0.3214921
6         NA        NA        NA        NA        NA
7  0.3214921 0.1189026 0.1189026 0.3214921 0.3214921
8  0.3214921        NA        NA 0.3214921 0.3214921
9        NA 0.1189026 0.1189026        NA        NA

I would like to pick the first two non-NA values of each row. What should I do?

The return may look like this:

 [1,] 0.1189026 0.1189026
 [2,] 0.1189026 0.1189026
 [3,]        NA        NA
 [4,]        NA        NA
 [5,] 0.3214921 0.3214921
 [6,]        NA        NA
 [7,] 0.3214921 0.1189026
 [8,] 0.3214921 0.3214921
 [9,] 0.1189026 0.1189026

Upvotes: 0

Views: 52

Answers (2)

Andre Elrico
Andre Elrico

Reputation: 11480

alternative:

library(magrittr)

DF %>% t %>% data.frame %>% lapply(function(x)head(x[!is.na(x)],2)) %>% do.call(rbind,.)

result:

#          [,1]      [,2]
# X2  0.1189026 0.1189026
# X3  0.1189026 0.1189026
# X6  0.3214921 0.3214921
# X8  0.3214921 0.1189026
# X9  0.3214921 0.3214921
# X10 0.1189026 0.1189026

Upvotes: 1

whalea
whalea

Reputation: 301

you can try this:

apply(df, 1, function(x) x[!is.na(x)][1:2])

or for transposed result:

t(apply(df, 1, function(x) x[!is.na(x)][1:2]))

Upvotes: 1

Related Questions