如何创建具有已定义行数的data.frame?

时间:2016-11-10 13:38:44

标签: r dataframe

我想创建一个数据框,我知道它将提前有多少行。以下代码创建"空"数据框:

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

现在如何创建具有10行和初始值的数据框: 整数为0,&#34; 0&#34;因素?

3 个答案:

答案 0 :(得分:3)

只需初始化数据框,然后执行

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

结果将是

> 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

答案 1 :(得分:2)

您可以使用如下初始化值:

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

答案 2 :(得分:0)

你也可以这样做:

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"))

会给你:

   # 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