簡體   English   中英

根據R中的多個條件創建列

[英]Create column based on multiple conditions in r

我有一個包含3列的數據框:個人ID,行程(按ID排序)和草料(是或否):

example <- data.frame(IDs = c(rep("A",30),rep("B",30)), 
                  timestamp = seq(c(ISOdate(2016,10,01)), by = "day", length.out = 60),
                  trip = c(rep("1",15),rep("2",15)), 
                  forage = c(rep("Yes",3),rep("No",5),rep("Yes",3),rep("No",4),rep("Yes",7),rep("No",8)))

我想創建兩個單獨的列,其中將列出每次觀察的覓食事件。 在第一列中,我想為ID和行程中的覓食=“ yes”編號每個觀察值(因此,個人中的每個行程將有x次覓食事件,對於個人中的下一個行程,將從“ 1”重新開始) 。 該列看起來像:

example$forageEvent1 <- c(rep(1,3),rep("NA",5),rep(2,3),rep("NA",4),rep(1,7),rep("NA",8),rep(1,3),rep("NA",5),rep(2,3),rep("NA",4),rep(1,7),rep("NA",8))

第二列將僅通過ID對覓食事件進行編號:

example$forageEvent2 <- c(rep(1,3),rep("NA",5),rep(2,3),rep("NA",4),rep(3,7),rep("NA",8),rep(1,3),rep("NA",5),rep(2,3),rep("NA",4),rep(3,7),rep("NA",8))

我可以將子集/管道分解為個人,然后跳閘並嘗試了ifelse(),但不知道如何編寫將創建事件序列的代碼。 謝謝大家

編輯:下面的代碼(從注釋中編輯)接近。 但是,它以“ Forage0”而不是“ Forage1”開頭打印。

library(dplyr)
Test_example <- example %>%
  group_by(IDs) %>%
  mutate(
  ForagebyID = case_when(
   forage == "Yes" ~ "Forage",
   forage == "No" ~"NonForage"),
  rleid = cumsum(ForagebyID != lag(ForagebyID, 1, default = "NA")), 
 ForagebyID = case_when(
  ForagebyID == "Forage" ~ paste0(ForagebyID, rleid %/% 2),
  TRUE ~ "NonForage"),
rleid = NULL
)

我認為這將滿足您的要求:

library(dplyr)

example <- data.frame(IDs = c(rep("A",30),rep("B",30)), 
                      timestamp = seq(c(ISOdate(2016,10,01)), by = "day", length.out = 60),
                      trip = c(rep("1",15),rep("2",15)), 
                      forage = c(rep("Yes",3),rep("No",5),rep("Yes",3),rep("No",4),rep("Yes",7),rep("No",8)))

Test_example <- example %>%
  arrange(IDs, timestamp) %>%
  group_by(IDs, trip) %>%
  mutate(forageEvent1 = case_when(forage == "No" ~ 0,
                                  TRUE ~ cumsum(forage != lag(forage, default = 1)) %/% 2 + 1)) %>%
  group_by(IDs) %>%
  mutate(forageEvent2 = case_when(forage == "No" ~ 0,
                                  TRUE ~ cumsum(forage != lag(forage, default = 1)) %/% 2 + 1))

暫無
暫無

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

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