简体   繁体   中英

Create “row” from first non-NA value in an R data frame

I want to create a "row" containing the first non-NA value that appears in a data frame. So for example, given this test data frame:

test.df <- data.frame(a=c(11,12,13,14,15,16),b=c(NA,NA,23,24,25,26), c=c(31,32,33,34,35,36), d=c(NA,NA,NA,NA,45,46))
test.df
   a  b  c  d
1 11 NA 31 NA
2 12 NA 32 NA
3 13 23 33 NA
4 14 24 34 NA
5 15 25 35 45
6 16 26 36 46

I know that I can detect the first appearance of a non-NA like this:

first.appearance <- as.numeric(sapply(test.df, function(col) min(which(!is.na(col)))))
first.appearance
[1] 1 3 1 5

This tells me that the first element in column 1 is not NA, the third element in column 2 is not NA, the first element in column 3 is not NA, and the fifth element in column 4 is not NA. But when I put the pieces together, it yields this (which is logical, but not what I want):

> test.df[first.appearance,]
     a  b  c  d
1   11 NA 31 NA
3   13 23 33 NA
1.1 11 NA 31 NA
5   15 25 35 45

I would like the output to be the first non-NA in each column. What is a base or dplyr way to do this? I am not seeing it. Thanks in advance.

   a  b  c  d
1 11 23 31 45

We can use

library(dplyr)
test.df %>% 
    slice(first.appearance) %>%
    summarise_all(~ first(.[!is.na(.)]))
#   a  b  c  d
#1 11 23 31 45

Or it can be

test.df %>% 
     summarise_all(~ min(na.omit(.)))
#   a  b  c  d
#1 11 23 31 45

Or with colMins

library(matrixStats)
colMins(as.matrix(test.df), na.rm = TRUE)
#[1] 11 23 31 45

You can use:

library(tidyverse)
df %>% fill(everything(), .direction = "up") %>% head(1)

       a     b     c     d
  <dbl> <dbl> <dbl> <dbl>
1    11    23    31    45

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM