Johnny Johansson Johnny Johansson - 27 days ago 16
R Question

How to create data.frame with defined number of rows?

I want to create a data frame and I know how many rows it is going to have in advance. Following code creates "empty" data frame:

result.data.frame <- data.frame(TrusterID = integer(),
TrusteeID = integer(),
RTT = integer(),
RTD = integer(),
RDT = integer(),
RDD = integer(),
TrustValue = factor(levels = c("1", "-1", "0")))


Now how to create data frame like that with 10 rows and initial values:
0 for integers and "0" for factor?

Answer

Just initialise the data frame as you have already, and then do

result.data.frame[1:10, ] <- 0

The result of this will be

> str(result.data.frame)
'data.frame':   10 obs. of  7 variables:
 $ TrusterID : num  0 0 0 0 0 0 0 0 0 0
 $ TrusteeID : num  0 0 0 0 0 0 0 0 0 0
 $ RTT       : num  0 0 0 0 0 0 0 0 0 0
 $ RTD       : num  0 0 0 0 0 0 0 0 0 0
 $ RDT       : num  0 0 0 0 0 0 0 0 0 0
 $ RDD       : num  0 0 0 0 0 0 0 0 0 0
 $ TrustValue: Factor w/ 3 levels "1","-1","0": 3 3 3 3 3 3 3 3 3 3