之前我问了一个类似的问题,但看起来我还不够清楚。我有一个32列的data.frame。我想在符合此特定条件的每一行下面创建一个重复的行
df$resting == "toolong".
根据DWin的建议,我使用以下代码完成了此操作。
df[ unlist(mapply( rep, rownames(df), 1+(df$resting=="toolong"))) , ]
效果不错但现在我需要更改新创建的重复行“strong”行 AND 的某些值。父行的变量操作和时间需要设置为
action <- "for"
time <- 60
重复的行需要将变量操作和时间设置为
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
谢谢,蒂姆
答案 0 :(得分: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