Create columns in R from another where some values are null

7

I'm wanting to create a column from another in the R where some of the rows have no value. The column should be constructed as follows: if the row of the base column has value, it will fetch that same value, otherwise it should fetch the information from the previous row of that new column. Could someone help me?

    
asked by anonymous 14.08.2014 / 21:10

2 answers

4

You can use the na.locf function of the zoo package. Example:

library(zoo)
x <- c(1, NA, NA, 2, NA, 3, 4)
na.locf(x)

Result:

[1] 1 1 1 2 2 3 4
    
15.08.2014 / 01:53
1

An alternative only with base functions that could be used for values other than NA:

x <- c(1, NA, NA, 2, NA, 3, 4)

nao_eh_na <- !is.na(x)
x_indices <- cumsum(nao_eh_na)
x_vals <- x[nao_eh_na]

x_vals[x_indices]

Result:

[1] 1 1 1 2 2 3 4
    
25.09.2014 / 04:26