EmKayDee
EmKayDee

Reputation: 183

R - filling a cell with the value from the previous column

I have a dataframe like this

x <- c(1, 0, 0, 0, 2, 0, 0, 3, 0, 0, 0)
y <- c(10:20)
dat <- rbind(x, y)

I don't want the X row to contain 0s. Instead, I would like to replace the 0s with the value from the most recent non-zero column.

The expected output is

1    1    1    1    2    2    2    3    3     3     3
10   11   12   13   14   15   16   17   18    19    20

This is similar to the solution found here, but operating column-wise rather than row-wise.

Thanks!

Upvotes: 3

Views: 407

Answers (2)

Andre Elrico
Andre Elrico

Reputation: 11490

step 1: replace all zeros with NA because, ...

dat[1, dat[1,] == 0] <- NA

step 2: ... you can then use a function that is esp. designed to do what you want with NA-values

dat[1, ] <- zoo::na.locf(unlist(dat[1,]))

# dat[1, ] <- zoo::na.locf(dat[1, ]) 

result:

#  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
#x    1    1    1    1    2    2    2    3    3     3     3
#y   10   11   12   13   14   15   16   17   18    19    20

Since your example was a matrix and you possibly have a data.frame for your real data. Make sure you ?unlist your data.frame-row into a vector, so zoo::na.locf can function as desired.

Upvotes: 4

akrun
akrun

Reputation: 887541

Here is an option with tidyverse, where we transpose the data, and use fill on all the column, transpose it back

library(tidyverse)
dat %>%
     t %>% 
     as.data.frame %>% 
     na_if(., 0) %>% 
     fill(!!! rlang::syms(names(.))) %>%
     t

Upvotes: 2

Related Questions