Reputation:
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?
Upvotes: 2
Views: 201
Reputation: 12937
You could also do:
n <- 10
result.data.frame <- data.frame(TrusterID = integer(n),
TrusteeID = integer(n),
RTT = integer(n),
RTD = integer(n),
RDT = integer(n),
RDD = integer(n),
TrustValue = replace(factor(levels = c("1", "-1", "0"))[1:n],1:n,"0"))
which will give you:
# TrusterID TrusteeID RTT RTD RDT RDD TrustValue
# 1 0 0 0 0 0 0 0
# 2 0 0 0 0 0 0 0
# 3 0 0 0 0 0 0 0
# 4 0 0 0 0 0 0 0
# 5 0 0 0 0 0 0 0
# 6 0 0 0 0 0 0 0
# 7 0 0 0 0 0 0 0
# 8 0 0 0 0 0 0 0
# 9 0 0 0 0 0 0 0
# 10 0 0 0 0 0 0 0
Upvotes: 0
Reputation: 14346
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
Upvotes: 3
Reputation: 1721
You can use initialize the values as follows:
val <- as.integer (rep(0,10))
result.data.frame <- data.frame(TrusterID = val,
TrusteeID = val,
RTT = val,
RTD = val,
RDT = val,
RDD = val,
TrustValue = factor(as.factor(rep(0,10)),
levels = c("1", "-1", "0")))
> str(result.data.frame)
'data.frame': 10 obs. of 7 variables:
$ TrusterID : int 0 0 0 0 0 0 0 0 0 0
$ TrusteeID : int 0 0 0 0 0 0 0 0 0 0
$ RTT : int 0 0 0 0 0 0 0 0 0 0
$ RTD : int 0 0 0 0 0 0 0 0 0 0
$ RDT : int 0 0 0 0 0 0 0 0 0 0
$ RDD : int 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
Upvotes: 2