简体   繁体   English

R - 使用上一列中的值填充单元格

[英]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. 我不希望X行包含0。 Instead, I would like to replace the 0s with the value from the most recent non-zero column. 相反,我想用最近的非零列中的值替换0。

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! 谢谢!

step 1: replace all zeros with NA because, ... 第1步: NA替换全零,因为......

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

step 2: ... you can then use a function that is esp. 第2步: ...然后你可以使用特别的功能。 designed to do what you want with NA -values 旨在通过NA您想要的操作

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. 由于您的示例是matrix ,因此您可能拥有实际数据的data.frame Make sure you ?unlist your data.frame-row into a vector, so zoo::na.locf can function as desired. 确保你将data.frame-row ?unlist列表转换为vector,因此zoo::na.locf可以根据需要运行。

Here is an option with tidyverse , where we transpose the data, and use fill on all the column, transpose it back 这是一个使用tidyverse的选项,我们在其中转置数据,并使用fill所有列,将其转置回来

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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