将特定值替换为上行中的值

问题描述 投票:0回答:2

我有一个大表,其中有几列带有“-”。我想将“-”替换为同一列中上行的值

library(tidyverse)

# This is the df I have
df <- data.frame(stringsAsFactors=FALSE,
                my = c("a", "a", "a", "-", "b", "b", "b", "-", "c", "c", "c", "-"),
               bad = c("d", "d", "d", "-", "e", "e", "e", "-", "f", "f", "f", "-"),
             table = c("g", "g", "g", "-", "h", "h", "h", "-", "i", "i", "i", "-")
      )

# This is the desired output:
output_df <- data.frame(stringsAsFactors=FALSE,
                       my = c("a", "a", "a", "a", "b", "b", "b", "b", "c", "c", "c", "c"),
                      bad = c("d", "d", "d", "d", "e", "e", "e", "e", "f", "f", "f", "f"),
                    table = c("g", "g", "g", "g", "h", "h", "h", "h", "i", "i", "i", "i")
             )


# What I have tried unsuccessfully:

df %>% 
  mutate_at(c("my", "bad", "table"), .funs = str_replace("-", NA))

我对这个有点困惑......有什么想法吗?

r tidyverse
2个回答
3
投票

fill
更改为
-
 后,一个选项是 
NA

library(tidyverse)
df %>% 
   mutate_all(na_if, "-") %>% 
   fill(my, bad, table)
   # orif there are many columns
   # fill(!!! rlang::syms(names(.)))
   # or as H1 suggested
   # fill(everything())
#   my bad table
#1   a   d     g
#2   a   d     g
#3   a   d     g
#4   a   d     g
#5   b   e     h
#6   b   e     h
#7   b   e     h
#8   b   e     h
#9   c   f     i
#10  c   f     i
#11  c   f     i
#12  c   f     i

0
投票

还使用

na.locf
包中的
zoo

require(zoo)
apply(df, 2, function(x) na.locf(ifelse(x=='-',NA,x)))
© www.soinside.com 2019 - 2024. All rights reserved.