-1

我之前问过类似的问题,但似乎我不够清楚。我有一个 32 列的 data.frame。我想在满足此特定条件的每一行下方创建一个重复的行

df$resting == "toolong".

根据 DWin 的建议,我使用以下代码完成了此操作。

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

这工作得很好,但现在我需要更改“父”行新创建的重复行的一些值。父行的变量actiontime需要设置为

action <- "for"
time <- 60

重复行需要将变量actiontime设置为

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.

这是一个显示数据结构的示例 data.frame(原始数据库中有更多列)。

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)

这是最终的 df 应该是什么样子。

    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

谢谢,蒂姆

4

1 回答 1

1

我使用了字符向量(正如我在前面的答案中描述的那样):

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
于 2013-10-18T21:07:30.227 回答