【问题标题】:Mutate column based on any lagged value of other column in R根据 R 中其他列的任何滞后值改变列
【发布时间】:2020-12-02 16:10:31
【问题描述】:

我认为应该是一项非常简单的数据转换任务,但我遇到了一些问题。 我有一个看起来像这样的数据框:

df
  council_name year treat
1    Southwark 2008     1
2    Southwark 2009     0
3    Southwark 2010     1
4      Lambeth 2006     0
5      Lambeth 2007     1
6      Lambeth 2008     0
7    Yorkshire 2006     0
8    Yorkshire 2007     0
9    Yorkshire 2008     0

我正在尝试获取一个新变量,例如 pre.post,如果理事会已经拥有值 1,则为 year1 的任何较低值 treat。基本上我想要pre.post == 1 如果council 之前有过year treat == 1

这就是我要找的:

df.desired
  council_name year treat pre.post
1    Southwark 2008     1        1
2    Southwark 2009     0        1
3    Southwark 2010     1        1
4      Lambeth 2006     0        0
5      Lambeth 2007     1        1
6      Lambeth 2008     0        1
7    Yorkshire 2006     0        0
8    Yorkshire 2007     0        0
9    Yorkshire 2008     0        0

基本上所有在任何以前时间处理 == 1 的理事会都得到 pre.post == 1。 我尝试了不同的方法,例如:

library(dplyr)

df%>%
group_by(council_name)%>%
arrange(year)%>%
mutate(pre.post = ifelse(any(lag(year) = 1), 1, 0))

但似乎没有什么能完全满足我的要求。 谢谢!

【问题讨论】:

    标签: r dataframe tidyverse dplyr


    【解决方案1】:

    等价地,找到第一个治疗年份,并为之后的每一年分配 1。

    df %>% group_by(council_name) %>% mutate(pre.post = +(year >= min(year[treat == 1])))
    

    输出

    # A tibble: 9 x 4
    # Groups:   council_name [3]
      council_name  year treat pre.post
      <chr>        <int> <int>    <int>
    1 Southwark     2008     1        1
    2 Southwark     2009     0        1
    3 Southwark     2010     1        1
    4 Lambeth       2006     0        0
    5 Lambeth       2007     1        1
    6 Lambeth       2008     0        1
    7 Yorkshire     2006     0        0
    8 Yorkshire     2007     0        0
    9 Yorkshire     2008     0        0
    Warning messages:
    1: Problem with `mutate()` input `pre.post`.
    i no non-missing arguments to min; returning Inf
    i Input `pre.post` is `+(year >= min(year[treat == 1]))`.
    i The error occurred in group 3: council_name = "Yorkshire". 
    2: In min(year[treat == 1]) :
      no non-missing arguments to min; returning Inf
    

    当我们将某个东西与设置为Infmin(integer()) 进行比较时,我们会收到此警告消息。 IMO,您可以忽略它,因为这样的比较不会破坏我们的逻辑。

    【讨论】:

    • 谢谢!但这对我不起作用,我收到以下错误:mutate() 输入问题pre.post。 ℹ min 没有不可缺少的参数;返回 Inf ℹ 输入 pre.post+(year &gt;= min(year[treat == 1]))。 ℹ 错误发生在第 46 组:code.fct = "E06000047".no non-missing arguments to min;返回
    • code.fct 等价于上例中的 Council_name 变量
    • 你确定这是一个错误吗?我认为这只是一个警告消息,与我上面显示的相同。没关系。即使有该消息,您也应该得到结果。 @AntVal
    • 你是对的,无论如何它都能解决问题。对不起!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 2023-01-02
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    相关资源
    最近更新 更多