简体   繁体   中英

Want to subset dataframe from beginning to certain value

I have a dataframe with induction and observation data, which I want to split into two. The induction goes from the first row to the row with Behavior value "e" and the second has the row to the end.

##      Time Behavior
## 1     1.0        D
## 2    46.0        r
## 3   104.1        r
## 4   146.4        r
## 5   164.6        r
## 6   204.5        r
## 7   248.7        r
## 8   261.8        a
## 9   337.2        x
## 10  392.7        a
## 11  609.8        e
## 12  630.6        r
## 13  661.9        u
## 14  664.5        a
## 15  745.6        r
## 16  769.9        r
## 17 1986.1        a

I want D -> e in one, and e -> end into a another.

 indx <- grep("e", dat[,2])
 lst <- setNames( lapply(Map(`:`, c(1,indx), c(indx,nrow(dat))),function(i) dat[i,]),paste0("D",1:2))
 list2env(lst, envir=.GlobalEnv)#

  tail(D1,2)
  #     Time Behavior
  #10 392.7        a
  #11 609.8        e
 head(D2,2)
  #    Time Behavior
  #11 609.8        e
 # 12 630.6        r

If they are subsequent, you could also do

df[1:which(df$Behavior == "e"),] -> first
df[-c(1:which(df$Behavior == "e")),] -> second

This puts e in the first data frame only


And with e in both:

df[1:which(df$Behavior == "e"),] -> first
df[-c(1:which(df$Behavior == "e")-1),] -> second

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