我如何在R中创建一个循环,在 Dataframe 中搜索包含某些值的文件,并将它们子集化?

pod7payv  于 2023-11-14  发布在  其他
关注(0)|答案(2)|浏览(155)

假设我有这样的数据:

data <- data.frame(
  Setting = c("start", "continue focal", "end", "start", "continue focal", "end", "start", "continue focal", "end", "start", "continue focal", "end"),
  Behaviour = c("grooming", "sleep", "fight", "grooming", "sleep", "fight", "grooming", "sleep", "fight", "grooming", "sleep", "fight")
)

字符串
乍一看,我在这里看到了4个行的子集(从start开始,到end结束)。我可以做些什么来提取这4个子集,以便将它们单独作为 Dataframe ?
我试过创建一个while循环,所以它逐行搜索是否出现某些值(开始和结束),然后它们之间的所有内容(包括它们)都转换为新的 Dataframe 。虽然,我发现自己真的卡住了,因为我不能让这个工作。

7lrncoxx

7lrncoxx1#

如果我理解了这个问题,这里有一个可能的解决方案。
1.创建一个新序列启动时的指示器
1.计算指标变量的累计和
1.使用split根据具有累积和的变量剪切数据框

data <- data.frame( Setting = c("start", "continue focal", "end", "start", "continue focal", "end", "start", "continue focal", "end", "start", "continue focal", "end"),
                    Behaviour = c("grooming", "sleep", "fight", "grooming", "sleep", "fight", "grooming", "sleep", "fight", "grooming", "sleep", "fight") )

dataGrouped<-data %>%
  dplyr::mutate(newStart = ifelse(Setting=="start",1,0)) %>%
  dplyr::mutate(cumulativeSum = cumsum(newStart))
  
split(dataGrouped,dataGrouped$cumulativeSum)

字符串

kh212irz

kh212irz2#

或者,请尝试以下代码
步骤:
1.派生具有序列号的var2
1.用序列号创建一个向量

  1. map2导出4个dfs
data <- data.frame(
  Setting = c("start", "continue focal", "end", "start", "continue focal", "end", "start", "continue focal", "end", "start", "continue focal", "end"),
  Behaviour = c("grooming", "sleep", "fight", "grooming", "sleep", "fight", "grooming", "sleep", "fight", "grooming", "sleep", "fight")
) %>% mutate(var1=ifelse(Setting=='start', rleid(Setting),NA)) %>% fill(var1) %>% 
  mutate(var2=rleid(var1))

vars <- levels(factor(data$var2))

map2('data',vars, \(x,y) {
  x1 <- get(x)
  x2 <- x1[x1$var2==y,]
  assign(paste0('df',y),x2, envir = globalenv())
}
)

[[1]]
         Setting Behaviour var1 var2
1          start  grooming    1    1
2 continue focal     sleep    1    1
3            end     fight    1    1

[[2]]
         Setting Behaviour var1 var2
4          start  grooming    4    2
5 continue focal     sleep    4    2
6            end     fight    4    2

[[3]]
         Setting Behaviour var1 var2
7          start  grooming    7    3
8 continue focal     sleep    7    3
9            end     fight    7    3

[[4]]
          Setting Behaviour var1 var2
10          start  grooming   10    4
11 continue focal     sleep   10    4
12            end     fight   10    4

字符串

相关问题