简体   繁体   中英

Is there a function that will extend values in a column into NA positions? [R]

Here is an example of my Data. I am trying to extend the existing Hour_of_Day values down to fill in the missing information. I would appreciate some guidance in this area. Thank You!

Hour_of_Day       Counter Name People In People Out Day_of_Week Month_Day  Year
1     12:00 AM               Main         4          2    Thursday  April 01  2021
2         <NA>            FLgate1         3          2    Thursday  April 01  2021
3         <NA>   FLgate1.Counter1         0          0    Thursday  April 01  2021
4         <NA>   FLgate1.Counter2         3          2    Thursday  April 01  2021
5         <NA>   FLgate2.Counter1         0          0    Thursday  April 01  2021
6         <NA>   FLgate2.Counter2         0          0    Thursday  April 01  2021
7         <NA>            FLgate2         1          0    Thursday  April 01  2021
8         <NA> RFIDGateFL3.Aisle1         0          0    Thursday  April 01  2021
9         <NA> RFIDGateFL3.Aisle2         1          0    Thursday  April 01  2021
10        <NA> RFIDGateFL3.Aisle3         0          0    Thursday  April 01  2021
11     1:00 AM               Main         0          0    Thursday  April 01  2021
12        <NA>            FLgate1         0          0    Thursday  April 01  2021
13        <NA>   FLgate1.Counter1         0          0    Thursday  April 01  2021
14        <NA>   FLgate1.Counter2         0          0    Thursday  April 01  2021
15        <NA>   FLgate2.Counter1         0          0    Thursday  April 01  2021
16        <NA>   FLgate2.Counter2         0          0    Thursday  April 01  2021
17        <NA>            FLgate2         0          0    Thursday  April 01  2021
18        <NA> RFIDGateFL3.Aisle1         0          0    Thursday  April 01  2021

Here is a base R option with cumsum + is.na

transform(
  df,
  Hour_of_Day = c(NA, na.omit(Hour_of_Day))[cumsum(!is.na(Hour_of_Day)) + 1]
)

We can use fill from tidyr

library(tidyr)
fill(df1, Hour_of_Day)

Or use na.locf0 from zoo

library(zoo)
df1$Hour_of_Day <- na.locf0(df1$Hour_of_Day)

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