有条件地根据前一行重命名该值

时间:2016-07-25 14:37:40

标签: r conditional rename

我有一个数据框 df

Event       Code
Picture     no$
Picture     value
Picture     $
Picture     value
Picture     no$
Picture     value
Picture     no$
Picture     value
Picture     $
Picture     value

我想将重命名为奖励 no_reward ,具体取决于前一行。如果它是 $ 那么奖励,如果它是没有$ 那么 no_reward

最好的方法是什么?

3 个答案:

答案 0 :(得分:4)

另一个想法,

df1$Code[c(FALSE, TRUE)] <- ifelse(df1$Code[c(TRUE, FALSE)] == 'no$', 'no_reward', 'reward')
df1
#     Event      Code
#1  Picture       no$
#2  Picture no_reward
#3  Picture         $
#4  Picture    reward
#5  Picture       no$
#6  Picture no_reward
#7  Picture       no$
#8  Picture no_reward
#9  Picture         $
#10 Picture    reward

注意:这假定每$no$value跟随

答案 1 :(得分:0)

以下是使用ifelse,子集和which

的方法
df$Code[which(df$Code=="value")] <- 
       ifelse(df$Code[which(df$Code=="value") - 1] == "$", "reward", "no_reward")

或者可能更快的方法,不使用ifelse

df$Code[which(df$Code=="value")] <-
      c("reward", "no_reward")[(df$Code[which(df$Code=="value") - 1] == "$") + 1]

两者都返回

df
     Event      Code
1  Picture       no$
2  Picture no_reward
3  Picture         $
4  Picture    reward
5  Picture       no$
6  Picture no_reward
7  Picture       no$
8  Picture no_reward
9  Picture         $
10 Picture    reward

数据

df <- read.table(header=T, text="Event       Code
Picture     no$
Picture     value
Picture     $
Picture     value
Picture     no$
Picture     value
Picture     no$
Picture     value
Picture     $
Picture     value", as.is=T)

答案 2 :(得分:0)

您也可以使用data.tabledata.table::shift

require(data.table)

dt = data.table(Event = 'Picture',
                Code = c('no$', 'value', '$', 'value', 'no$', 'value', 'no$', 'value', '$', 'value'))

dt[, Code_l1 := shift(Code)]
dt[Code_l1 == '$', Code := 'reward']
dt[Code_l1 == 'no$', Code := 'no_reward']
dt[, Code_l1 := NULL]