[英]R Adding one new row for each subject
I would like to add one new row for each of the subjects in my dataframe, which looks something like this: 我想为数据框中的每个主题添加一个新行,如下所示:
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
I want to add a new row for each subject with a time = 0 and value = 0, giving this: 我想为每个主题添加一个新行,其中时间= 0,值= 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
I have a lot of subjects with a lot of gaps in their subject numbers, and want do this for all of them in a reasonable way. 我有很多科目,科目编号上有很多空白,并且希望以合理的方式为所有这些科目设置。 Any suggestions?
有什么建议么?
Thank you in advance. 先感谢您。
Sincerily, 顺祝商祺
ykl k
I would just rbind
in the new values (not sure why you specified all your values as character values, here I changed them to numeric) 我只想
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")
)
this puts them at the bottom, but you could re-sort of you like 这使它们位于底部,但是您可以像这样重新排序
DF2[order(DF2$subject, DF2$time), ]
You can also use interleave
from the "gdata" package: 您也可以从“ gdata”包中使用
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
This uses @MrFlick's sample data. 这使用@MrFlick的样本数据。
DF <- data.frame(
Subject = c(1,5,10),
time = c(2, 2.25, 2.5),
value = c(3, 17, 9)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.