【问题标题】:Generating a new variable in R where the nth observation depends on the n-1th observation of another column在 R 中生成一个新变量,其中第 n 个观察值取决于另一列的第 n-1 个观察值
【发布时间】:2012-11-29 22:15:36
【问题描述】:

假设我有一个看起来像这样的数据框:

>df
city  year  ceep
  1    1      1
  1    2      1
  1    3      0
  1    4      1
  1    5      0
  2    1      0
  2    2      1
  2    3      1
  2    4      0
  2    5      1
  3    1      1
  3    2      0
  3    3      1
  3    4      0
  3    5      1

现在我想创建一个新变量 'veep',它取决于不同行中的 'city' 和 'ceep' 的值。例如,

veep=1 if ceep[_n-1]=1 & city=city[_n-1]
veep=1 if ceep[_n+2]=1 & ceep[_n+3]=1 & city=city[_n+3] 

其中n 是观察行。我不确定如何将这些条件翻译成 R 语言。我想我遇到问题的地方是选择观察行。我正在考虑以下代码:

df$veep[df$ceep(of the n-1th observation)==1 & city==city(n-1th observ.)] <- 1
df$veep[df$ceep(of the n+2th observation)==1 & df$ceep(of the n+3th observation)==1 &
city==city(n+3th observ.)] <- 1

#note: what's in parentheses is just to demonstrate where I'm having trouble 

谁能提供这方面的帮助?

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    这是一种写出逻辑步骤的方法。注意使用idx 来索引向量。这对于避免超出范围的索引是必要的。

    idx <- seq_len(nrow(df))
    
    # Set a default value for the new variable
    df$veep <- NA
    

    您的第一组逻辑条件不能应用于df 的第一行,因为索引n - 1 将是0,这不是有效的行索引。因此,使用tail(*, -1) 来挑选除veepcity 的第一个条目之外的所有条目,并使用head(*, -1) 挑选除ceepcity 的最后一个条目之外的所有条目。

    df[tail(idx, -1), "veep"] <- ifelse(
      head(df$ceep, -1) == 1 &
      tail(df$city, -1) == head(df$city, -1),
      1, tail(df$veep, -1))
    

    您的下一组条件不能应用于df 的最后三行,因为n + 3 将是无效索引。所以再次使用headtail 函数。一个棘手的部分是第一个ceep 语句基于n + 2,而不是n + 3,因此需要headtail 的组合。

    df[head(idx, -3), "veep"] <- ifelse(
      head(tail(df$ceep, -2), -1) == 1 &
      tail(df$ceep, -3) == 1 &
      head(df$city, -3) == tail(df$city, -3),
      1, head(df$veep, -3))
    
    > df$veep
     [1] NA  1  1 NA  1 NA NA  1  1 NA NA  1 NA  1 NA
    

    【讨论】:

    • 漂亮,但对新手来说是不是有点难?
    • @agstudy,你可能是对的。也许有些“解释”是为了。
    • @econlearner,我已经注释了上面的代码来解释 headtail 位。
    【解决方案2】:

    你可以像这样使用 for 循环

    df$veep <- 0   
    
    for (i in seq(nrow(df))){
     if (i > 1 & i < nrow(df)-2){
        if (df[i-1,"ceep"]==1 & df[i-1,"city"] == df[i,"city"])
           df[i,"veep"] <- 1
     }
    }
    

    【讨论】:

    • nrow(df) - 1怎么样?
    猜你喜欢
    • 1970-01-01
    • 2019-01-05
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多