【问题标题】:Assigning group ID to different number of rows each time in R每次在R中将组ID分配给不同数量的行
【发布时间】:2020-11-13 17:20:42
【问题描述】:

我有一些数据,其中不同的行数对应一个 ID(例如人)。看起来是这样的:

label      | response
-----------+------------
'consent'  |  'yes'
'age'      |  '34'
'gender'   |  'female'
'language' |  'english'
'education'|  'college'
'consent'  |  'yes'
'age '     |  '37'
'gender '  |  'male'
'language' |  'english'
'education'|  'high school'
'race'     |  'white'

这些响应对应于两个人,一个包含对种族的响应,而另一个没有。由于每个人都有consent 的答案,我想知道是否有办法根据同意标签分配个人 ID。例如。如果 label=consent,为每一行分配相同的 ID,直到下一次同意。例如,我希望数据如下所示:

label      | response   |  ID
-----------+------------+------
'consent'  |  'yes'     |  1 
'age'      |  '34'      |  1
'gender'   |  'female'  |  1
'language' |  'english' |  1
'education'|  'college' |  1
'consent'  |  'yes'     |  2
'age '     |  '37'      |  2
'gender '  |  'male'    |  2
'language' |  'english' |  2
'education'|  'HS'      |  2
'race'     |  'white'   |  2

我尝试了许多 for 循环和 if 语句,但还没有找到方法。希望可以做到。

谢谢!

【问题讨论】:

    标签: r data-management


    【解决方案1】:

    这行得通吗:

    library(dplyr)
    df %>% mutate(ID = cumsum(label == 'consent'))
    # A tibble: 11 x 3
       label     response       ID
       <chr>     <chr>       <int>
     1 consent   yes             1
     2 age       34              1
     3 gender    female          1
     4 language  english         1
     5 education college         1
     6 consent   yes             2
     7 age       37              2
     8 gender    male            2
     9 language  english         2
    10 education high school     2
    11 race      white           2
    

    【讨论】:

    • 是的!非常感谢!
    猜你喜欢
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 2018-07-13
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多