gpt4 book ai didi

r - 使用列名创建空的 data.frame

转载 作者:行者123 更新时间:2023-12-03 22:31:23 24 4
gpt4 key购买 nike

我正在尝试创建一个包含两列和未知行数的空数据框。我想指定列的名称。我运行了以下命令

dat <- data.frame("id"=numeric(),"nobs"=numeric())  

我可以通过运行来测试结果
> str(dat)
'data.frame': 0 obs. of 2 variables:
$ id : num
$ nobs: num

但是后来当我在以下命令中使用 rbind 将数据插入到这个数据框中时,列的名称也发生了变化
  for (i in id) {
nobs = nrow(na.omit(read.csv(files_list[i])))
dat = rbind(dat, c(i,nobs))
}

在 for 循环之后,这是 dat 的值
dat
X3 X243
1 3 243

str 命令显示以下内容
str(dat)

'data.frame': 1 obs. of 2 variables:
$ X3 : num 3
$ X243: num 243

谁能告诉为什么数据框中的列名会改变

编辑:

我解决问题的懒惰解决方案是在将数据绑定(bind)到我的 data.frame 的 for 循环之后运行以下命令
names(dat)[1] = "id"
names(dat)[2] = "nobs"

最佳答案

您应该尝试在 rbind() 中指定列名:
dat = rbind(dat, data.frame("id" = i, "nobs" = nobs))

关于r - 使用列名创建空的 data.frame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24899109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com