简体   繁体   中英

How to add a “group” column in R based on the row number

I have a large df which has count data generated from two different programs. This is an example of the df:

 Species variable  value
1      "Malassezia;globosa"      100  68126
2      "Aspergillus;nomius"      100  13977
3  "Mitosporidium;daphniae"      100   5953
4 "Penicillium;chrysogenum"      100      1
5                     Other      100    102
6      "Malassezia;globosa"      101 110268

In total there are 311 rows. I want to add another column titled "Program" which groups rows 1 to 186 as "HMS" and rows 187 to 311 as "MiCoP", for example:

 Species variable  value  Program
1      "Malassezia;globosa"      100  68126   HMS
2      "Aspergillus;nomius"      100  13977   HMS
3  "Mitosporidium;daphniae"      100   5953   HMS
4 "Penicillium;chrysogenum"      100      1   HMS
5                     Other      100    102   HMS
6      "Malassezia;globosa"      101 110268   HMS

If you want to assign groups based on row number, you can do:

df$Program <- NA #initialise
df$Program[1:186] <- "HMS"
df$Program[187:311] <- "MiCoP"

We can do this with case_when

library(dplyr)
df <- df %>%
        mutate(Program = case_when(row_number() < 187 ~ "HMS", 
                      between(row_number(), 187, 311) ~ "MiCoP"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM