我有一个包含这样一列的数据框:
他是dataframe的一个例子(真正的有多个列但是为此我只发布重要的列):
structure(list(frame = c(0L, 0L, 0L, 0L, 473047L, 0L, 473049L,0L, 0L, 473051L, 0L, 0L, 473052L, 0L, 473055L)), row.names = c(NA, -15L), class = "data.frame")
帧列表示帧编号。列中的 0 与后面的大数字属于同一帧。所以我想把前四个0改成473047,然后把下一个0改成473049,再把后面两个0改成473051,依此类推分析。
有人有关于如何在 base R 中或使用 tidyverse 执行此操作的提示吗?我想也许 for 循环/if 语句组合可以通过某种索引过程来工作,即
for the length of the frame column
if frame > 0
count back up the column and replace the preceding 0s with that number
但是我想不出除了这个伪代码之外的可能解决方案。任何帮助将不胜感激!
最佳答案
你可以试试这个,首先用 NA 替换零
library(dplyr)
library(tidyr)
dat %>%
mutate(frame = ifelse(frame == 0, NA, frame)) %>%
fill(frame, .direction = "up")
frame
1 473047
2 473047
3 473047
4 473047
5 473047
6 473049
7 473049
8 473051
9 473051
10 473051
11 473052
12 473052
13 473052
14 473055
15 473055
关于在数据帧的列中紧跟其后用数字替换前导 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72465363/