簡體   English   中英

如何根據行號在 R 中添加“組”列

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

我有一個很大的 df,其中包含從兩個不同程序生成的計數數據。 這是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

總共有 311 行。 我想添加另一個標題為“程序”的列,它將第 1 到 186 行分組為“HMS”,將第 187 到 311 行分組為“MiCoP”,例如:

 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

如果要根據行號分配組,可以執行以下操作:

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

我們可以用case_when做到這一點

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM