【问题标题】:How to identify the first and last occurrence across columns and record the position?如何识别跨列的第一次和最后一次出现并记录位置?
【发布时间】:2019-12-18 12:07:53
【问题描述】:

我想创建两个变量来标识多列中的第一次和最后一次出现。每一行都是一个人。每列都是重复的二元观察。列名指的是年龄 (1,3,5,8,11)。

这是一些数据:

structure(list(T1 = c(1, 0, 1), T3 = c(1, 1, 1), T5 = c(0, 1, 
1), T8 = c(1, 1, 0), T11 = c(1, 1, 1)), class = "data.frame", row.names = 
c(NA, 
-3L))

我想创建两个变量,第一个和最后一个,它们在观察第一个或最后出现时记录相应列(1、3、5、8 或 11)中的数字。因此,对于第 1 行,first=1;对于第 2 行,第一个 = 3。我不确定如何以宽格式执行此操作。

【问题讨论】:

  • 如果下面发布的解决方案是您的预期输出,请告诉我

标签: r


【解决方案1】:

tidyverse 选项可以将 row_number()gather 的列创建为长格式,删除 0 行并为每一行获取 firstlast 列。

library(dplyr)
library(tidyr)

df %>%
  mutate(row = row_number()) %>%
  gather(key, value, -row) %>%
  filter(value != 0) %>%
  mutate(key = sub("T", "", key)) %>%
  group_by(row) %>%
  summarise(first = first(key), 
            last = last(key)) %>%
  select(-row)

# first last 
#  <chr> <chr>
#1 1     11   
#2 3     11   
#3 1     11   

使用aggregate 的基本 R 方法

aggregate(col~row, which(df == 1, arr.ind = TRUE), function(x) names(df)[range(x)])

【讨论】:

    【解决方案2】:

    我建议将这些数据融合为data.tabledplyr 可以使用的格式。如果有一天您决定为此使用SQL,它也会很有用。

    library(data.table)
    
    dt <- data.table(dt)
    dt[, id := 1:.N]
    dt.t <- melt(dt, id.vars = "id", variable.name = "age")
    res <- dt.t[value == 1, .(first.observed = min(as.character(age)),
                    last.observed = max(as.character(age))), id]
    res
    #       id first.observed last.observed
    # 1:  1             T1            T8
    # 2:  2            T11            T8
    # 3:  3            T11            T5
    

    您的数据集中没有个人的 id 列,我为此示例创建了一个。

    【讨论】:

    【解决方案3】:

    我们可以使用max.col

    data.frame(first = sub("\\D+", "", names(df1)[max.col(df1, "first")]), 
                last = sub("\\D+", "", names(df1)[max.col(df1, "last")]))
    #     first last
    #1     1   11
    #2     3   11
    #3     1   11
    

    或使用apply

    t(apply(df1, 1, function(x) names(x)[range(which(as.logical(x)))]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-22
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 2016-03-04
      • 1970-01-01
      相关资源
      最近更新 更多