简体   繁体   English

在R中填充空数据框

[英]Fill an empty data frame in R

I want to create an empty data frame with one column holding character data and one column holding numeric data, and then populate that data frame. 我想创建一个空数据框,其中一列包含字符数据,一列包含数字数据,然后填充该数据框。

dat<-as.data.frame(cbind(character(3),vector("numeric",3)))
dat
for (i in 1:3)
{
  dat[i,1]<-as.character("f")
  dat[i,2]<-i
}

dat

The results are below. 结果如下。 As you can see I get all NA: 如你所见,我得到了所有NA:

> dat
    V1   V2
1 <NA> <NA>
2 <NA> <NA>
3 <NA> <NA>

Can you advise how to do it? 你能建议怎么做吗?

I don't know why you would want to do this, but here are some tips: 我不知道你为什么要这样做,但这里有一些提示:

  1. Don't use as.data.frame(cbind(...)) 不要使用as.data.frame(cbind(...))
  2. Make sure you use stringsAsFactors 确保使用stringsAsFactors
  3. Use spaces in your code (makes things easier to read). 在代码中使用空格(使事情更容易阅读)。

Thus, you can try: 因此,您可以尝试:

dat <- data.frame(character(3), numeric(3), stringsAsFactors = FALSE)
dat
#   character.3. numeric.3.
# 1                       0
# 2                       0
# 3                       0

for (i in 1:3)
  {
      dat[i,1]<-as.character("f")
      dat[i,2]<-i
  }

dat
#   character.3. numeric.3.
# 1            f          1
# 2            f          2
# 3            f          3

What about creating a really empty data frame and adding the appropriate data? 如何创建一个真正空的数据框并添加适当的数据呢?

dat <- as.data.frame(matrix(ncol=2, nrow=0))
for(i in 1:3) {
  dat[i,1] = as.character('f')
  dat[i,2] = i
}
dat
##  V1 V2
##1  f  1
##2  f  2
##3  f  3

我想你想用stingsAsFactors = F

dat<-as.data.frame(cbind(character(3),vector("numeric",3)), stringsAsFactors = F)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM