date time td number
20150102 80000 -1 0
20150102 80001 -1 2
20150102 80002 1 0
20150102 80003 1 3
20150102 80004 -1 0
I need to create append number of rows based on variable "number". And let date and time be the same as the numbered rows, while the variable td=0. I want the data like this:
date time td number
20150102 80000 -1 0
20150102 80001 -1 2
20150102 80002 1 0
20150102 80003 1 3
20150102 80004 -1 0
20150102 80001 0 NA
20150102 80001 0 NA
20150102 80003 0 NA
20150102 80003 0 NA
20150102 80003 0 NA
I'd generate each column, then bind them into a data frame, then bind them to the original dataframe! No looping required.
Assuming your data frame is called df
#Create the date and time using the number column directly.
date <- rep(df$date, times = df$number)
time <- rep(df$time, times = df$number)
#Combine these fields into a data frame and set td to all 0s and number to all NAs
appenddf <- data.frame(date = date, time = time, td = 0, number = NA)
#Bind the data for appending to the original data frame
df <- rbind(df, appenddf)