【问题标题】:Data Munging: Editing Rows on a Condition数据整理:根据条件编辑行
【发布时间】:2018-10-17 15:38:10
【问题描述】:

我希望根据其他一些变量的信息来编辑我的专栏之一。这是下面的数据和问题:

Current Data: 
time_played     Round     Type
NA                1        Pre
10                1        Post
NA                Bye      Pre
NA                Bye      Post
NA                3        Pre
96                3        Post
NA                4        Pre
79                4        Post

我想把它改成这种格式:

time_played     Round     Type
NA                1        Pre
10                1        Post
10                Bye      Pre
0                 Bye      Post
0                 3        Pre
96                3        Post
96                4        Pre
79                4        Post

也就是说:一轮的“Pre”等于前一轮的“Post”,Bye 被视为 Round,除了它的 Post 将只有 0 time_played

请让我知道如何在 R 上完成此操作

提前非常感谢您

【问题讨论】:

  • 您能否尝试更广泛地解释所需的输出?我不明白逻辑。

标签: r


【解决方案1】:

我们可以从tidyr使用fill

library(tidyverse)
df1 %>%
   mutate(time_played = replace(time_played, Round == "Bye" & 
              Type == "Post", 0)) %>%
   fill(time_played)
#   time_played Round Type
#1          NA     1  Pre
#2          10     1 Post
#3          10   Bye  Pre
#4           0   Bye Post
#5           0     3  Pre
#6          96     3 Post
#7          96     4  Pre
#8          79     4 Post

【讨论】:

    【解决方案2】:

    另一个(可能更快)dplyr 解决方案:

    df %>%
      mutate(time_played = ifelse(Type == "Pre" & lag(Type) == "Post", lag(time_played), 
                               ifelse(Round == "Bye" & Type == "Post", 0, time_played)),
             time_played = ifelse(lag(Round) == "Bye" & lag(time_played) == 0, 0, time_played))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 2016-11-23
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多