【问题标题】:Creating a new variable based on prior history根据先前的历史创建一个新变量
【发布时间】:2020-03-24 05:44:21
【问题描述】:

我有数据需要根据之前的历史创建一个变量,例如

 created<- c(2009,2010,2010,2011, 2012, 2011)
 person <- c(A, A, A, A, B, B)
 location<- c('London','Geneva', 'London', 'New York', 'London', 'London')
 df <- data.frame (created, person, location)

我想创建一个名为“现有”的变量,该变量考虑了前几年,看看他/她是否住在那个地方,如果这个地方很旧(他们住在那里),则给出 0 值。任何建议?

 library(dplyr) 
 df %>% group_by(person) %>% mutate (existing=0)

  existing<- c(1, 1, 0, 1, 0,1)

【问题讨论】:

  • 为什么第5行的值是1,而不是0? (最后一行相同)
  • 你说得对是0

标签: r dplyr data.table plyr tidyr


【解决方案1】:

根据来自OP的更新信息,我们需要先arrangeperson和年份(created)的数据,然后使用duplicated

library(dplyr)

df %>% 
   arrange(person, created) %>% 
   group_by(person) %>% 
   mutate(existing = +(!duplicated(location)))

#  created person location existing
#    <dbl> <fct>  <fct>       <int>
#1    2009 A      London          1
#2    2010 A      Geneva          1
#3    2010 A      London          0
#4    2011 A      New York        1
#5    2011 B      London          1
#6    2012 B      London          0

【讨论】:

  • 你能解释一下+是做什么的吗?
  • @Metariat duplicated 返回逻辑值。 + 提前将逻辑值转换为整数值。所以TRUE -> 1 和 FALSE 为 0。检查 +TRUE+FALSE
  • 我认为您需要在解决方案中考虑年份
  • @Metariat 我最初也这么认为,但 OP 的预期输出并没有反映出这一点。在A 组的预期输出中,London 将 0 分配给 2010 而不是 2009,但B 组将 0 分配给 2011 而不是 2012。
【解决方案2】:

你可以试试,

with(df, ave(location, person, FUN = function(i)as.integer(!duplicated(i))))
#[1] "1" "1" "0" "1" "1" "0"

【讨论】:

    【解决方案3】:

    另一个dplyr 选项可能是:

    df %>%
     group_by(person, location) %>%
     mutate(existing = +(1:n() == 1))
    
      created person location existing
        <dbl> <fct>  <fct>       <int>
    1    2009 A      London          1
    2    2010 A      Geneva          1
    3    2010 A      London          0
    4    2011 A      New York        1
    5    2012 B      London          1
    6    2011 B      London          0
    

    如果需要排序:

    df %>%
     group_by(person, location) %>%
     arrange(created, .by_group = TRUE) %>%
     mutate(existing = +(1:n() == 1))
    

    【讨论】:

    • 我们可以在 2011 年之前按 2012 年创建的年份排序吗?
    • 你的意思是按降序排列吗?
    • 是的,我猜它是 A 2009-2011 的正确顺序,B 应该是 2011 和 2012 的顺序,谢谢
    • 当然可以df %&gt;% group_by(person, location) %&gt;% arrange(created, .by_group = TRUE) %&gt;% mutate(existing = +(1:n() == 1)) :)
    【解决方案4】:

    另一个使用data.table的选项:

    setDT(df)[order(person, created), existing := c(1L, rep(0L, .N-1L)), .(person, location)]
    

    输出:

       created person location existing
    1:    2009      A   London        1
    2:    2010      A   Geneva        1
    3:    2010      A   London        0
    4:    2011      A New York        1
    5:    2012      B   London        0
    6:    2011      B   London        1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      • 2019-09-28
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多