我想为我的数据框中的每个主题添加一个新行,如下所示:
Subject = c("1","5","10")
time = c("2", "2.25", "2.5")
value = c("3", "17", "9")
DF <- data.frame(Subject, time, value)
Subject time value
1 1 2 3
2 5 2.25 17
3 10 2.5 9
我想为每个主题添加一个新行,其中time = 0且value = 0,这样做:
Subject = c("1","1","5","5","10","10")
time = c("0","2","0", "2.25","0", "2.5")
value = c("0","3","0", "17","0", "9")
DF2 <- data.frame(Subject, time, value)
Subject time value
1 1 0 0
2 1 2 3
3 5 0 0
4 5 2.25 17
5 10 0 0
6 10 2.5 9
我有很多科目在他们的科目编号上有很多空白,并希望以合理的方式为所有科目做这件事。有什么建议吗?
提前谢谢。
Sincerily,
ykl
答案 0 :(得分:2)
我只会rbind
在新值中(不确定为什么将所有值都指定为字符值,在这里我将它们更改为数字)
DF <- data.frame(
Subject = c(1,5,10),
time = c(2, 2.25, 2.5),
value = c(3, 17, 9)
)
DF2 <- rbind(
DF,
data.frame(Subject = unique(DF$Subject), time="0", value="0")
)
这会把它们放在最底层,但你可以重新排序你喜欢
DF2[order(DF2$subject, DF2$time), ]
答案 1 :(得分:0)
您还可以使用&#34; gdata&#34;中的interleave
包:
library(gdata)
interleave(DF, data.frame(Subject = 0, time = 0, value = 0))
# Subject time value
# 1 1 2.00 3
# 11 0 0.00 0
# 2 5 2.25 17
# 1.1 0 0.00 0
# 3 10 2.50 9
# 1.2 0 0.00 0
这使用@ MrFlick的样本数据。
DF <- data.frame(
Subject = c(1,5,10),
time = c(2, 2.25, 2.5),
value = c(3, 17, 9)
)