Create columns in R from another where some values are null

Asked

Viewed 472 times

8

I want to create a column from another in the R, where part of the lines have no value. The column should be constructed as follows: if the row of the base column has value, it will look for the same value, otherwise it should look for information from the previous row of this new column. Could someone help me?

  • you tried something?

  • 1

    Cristiane, put an example illustrating the expected result, this helps to eliminate the ambiguity of the question. See here an example of how to improve the question. http://meta.pt.stackoverflow.com/questions/824/como-crea-um-exemplo-m%C3%Adnimo-reproduces%C3%Advel-em-r/825#825

  • 1

    Hi, Cristiane, if Rodrigo’s answer answered your question, you can accept it by clinging to the ok symbol on the left side of the answer!

2 answers

5

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

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

Upshot:

[1] 1 1 1 2 2 3 4

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]

Upshot:

[1] 1 1 1 2 2 3 4

Browser other questions tagged

You are not signed in. Login or sign up in order to post.