Вопрос

I asked a similar question before but it appears I was not clear enough. I have a data.frame with 32 columns. I want to create a duplicate row below each row that meets this certain criteria

df$resting == "toolong".

Following suggestions from DWin I have accomplished this using the following code.

df[ unlist(mapply( rep, rownames(df), 1+(df$resting=="toolong"))) , ]

That works well enough but now I need to alter some of the values of the "parent" row AND the newly created duplicate row. The variables action and time for the parent rows needs to be set to

action <- "for"
time <- 60

The duplicate rows need to have the variables action and time set to

action <- "l" # which is what it is already so this can be ignored for now
time <- "parent row time" - 60 # I am unsure how to code this.

Here is an example data.frame that shows the structure of the data (there are many more columns in the original database).

id <- c(1,1,1,1,2,2,2,3,3,3)
resting <- c("f","toolong","t","f","f","toolong","t","f","toolong","t")
time <- c(23,145,34,16,17,134,67,89,123,12)
act <- c("f","l","f","d","d","l","f","d","l","d")
df <- data.frame(id, resting, time, act)

Here is what the final df should look like.

    id resting time act
1    1       f   23   f
2    1 toolong   60   for
2.1  1 toolong   85   l
3    1       t   34   f
4    1       f   16   d
5    2       f   17   d
6    2 toolong   60   for
6.1  2 toolong   74   l
7    2       t   67   f
8    3       f   89   d
9    3 toolong   60   for
9.1  3 toolong   63   l
10   3       t   12   d

Thanks, Tim

Это было полезно?

Решение

I used character vectors (as I described in the earlier answer):

df <- data.frame(id, resting, time, act, stringsAsFactors=FALSE)

> df2 <- df[ unlist(mapply( rep, rownames(df), 1+(df$resting=="toolong"))) , ]
> df2[ df2$resting=="toolong" & !duplicated(df2) , "act"] <- "for"
> df2[ df2$resting=="toolong" & df2$act == "for" , "time"] <- 60
> df2[ df2$resting=="toolong" & df2$act == "l" , "time"] <- df2[ df2$resting=="toolong" & df2$act == "l" , "time"] - 60
> df2
    id resting time act
1    1       f   23   f
2    1 toolong   60 for
2.1  1 toolong   85   l
3    1       t   34   f
4    1       f   16   d
5    2       f   17   d
6    2 toolong   60 for
6.1  2 toolong   74   l
7    2       t   67   f
8    3       f   89   d
9    3 toolong   60 for
9.1  3 toolong   63   l
10   3       t   12   d
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top