2017-06-12 1 views
0

に遭遇するたびに、私は、このデータセット持って空の行を挿入:は、キーワードが

structure(list(Event = structure(c(2L, 2L, 1L, 2L, 2L, 2L, 2L, 
1L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L), .Label = c("Insert", 
"Ok"), class = "factor")), .Names = "Event", class = "data.frame", row.names = c(NA, 
-18L)) 

enter image description here

を私は「挿入」があるたびに下に空行を挿入したいと思います:

enter image description here

Rでこれを行うにはどうすればよいですか?

答えて

1

は、我々は論理ベクトル

i1 <- df1$Event == "Insert" 
Event <- unlist(lapply(split(df1$Event, 
    cumsum(c(TRUE, i1[-length(i1)]))), function(x) c(as.character(x), ""))) 
df2 <- data.frame(Event, stringsAsFactors=FALSE) 

を作成することも、別のオプションは、ここで

library(data.table) 
setDT(df1)[, grp := cumsum(shift(Event == "Insert", fill = TRUE)) 
     ][, .SD[c(seq_len(.N), .N+1)] , grp 
     ][is.na(Event), Event := "" 
     ][, grp := NULL][] 
#  Event 
# 1:  Ok 
# 2:  Ok 
# 3: Insert 
# 4:  
# 5:  Ok 
# 6:  Ok 
# 7:  Ok 
# 8:  Ok 
# 9: Insert 
#10:  
#11: Insert 
#12:  
#13:  Ok 
#14:  Ok 
#15:  Ok 
#16:  Ok 
#17: Insert 
#18:  
#19:  Ok 
#20:  Ok 
#21:  Ok 
#22: Insert 
#23:  
5

ある整数によってインデックス付けの第二の方法の基礎です。ここでは、提供されたデータがあれば、これは意味をなさないので、文字ベクトルを使って作業します。

# get integer index with repeats for observations with "Insert" 
myRows <- sort(c(seq_along(temp), which(temp == "Insert"))) 
# set second row index to missing 
is.na(myRows) <- duplicated(myRows) 

これで、文字ベクトルにインデックスを付けることができます。

temp[myRows] 
[1] "Ok"  "Ok"  "Insert" NA  "Ok"  "Ok"  "Ok"  "Ok"  "Insert" NA  "Insert" NA  "Ok"  
[14] "Ok"  "Ok"  "Ok"  "Insert" NA  "Ok"  "Ok"  "Ok"  "Insert" NA 

データ

temp <- 
structure(list(Event = structure(c(2L, 2L, 1L, 2L, 2L, 2L, 2L, 
1L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L), .Label = c("Insert", 
"Ok"), class = "factor")), .Names = "Event", class = "data.frame", row.names = c(NA, 
-18L)) 

temp <- as.character(temp$Event) 
0

ここでアイデアです:

mydf <- structure(list(Event = structure(c(2L, 2L, 1L, 2L, 2L, 2L, 2L, 
1L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L), .Label = c("Insert", 
"Ok"), class = "factor")), .Names = "Event", class = "data.frame", row.names = c(NA, 
-18L)) 

mydf$rowindex <- 1:nrow(mydf) 
mydf$repeats <- 1 
mydf$repeats[which(mydf$Event=="Insert")] <- 2 
mydf2 <- mydf[rep(mydf$rowindex,mydf$repeats),] 
mydf2[which(grepl("\\.",row.names(mydf2))),"Event"] <- NA 

は、このことができますなら、私に教えてください。

関連する問題