简体   繁体   English

R中的数据帧头是错误的

[英]Dataframe headers are wrong in R

I wrote a function that is supposed to return a dataframe. 我写了一个应该返回一个数据帧的函数。 Although the output is fine, the headers of the output are incorrect. 尽管输出很好,但是输出的标题不正确。 When I initialized the dataframe (output), I clearly labeled the two columns are 'id' and 'nobs'. 初始化数据帧(输出)时,我清楚地将两列标记为“ id”和“ nobs”。 However, in the output, the columns are labeled X30 and X932, respectively. 但是,在输出中,这些列分别标记为X30和X932。 Can someone help? 有人可以帮忙吗?

Here's my code 这是我的代码

complete <- function(directory, id) {
  output <- data.frame(id=character(),
                   nobs=character(), 
                   stringsAsFactors=FALSE)
  files <- list.files()
  for (i in id){
  mydata <- read.csv(files[i])
  nobs <- nrow(na.omit(mydata))
  tempVector <- c(i, nobs)
  output <- rbind(output, tempVector)
}

print(output)

}

I can't test without a reproducible example, but if you do tempVector <- data.frame(id=i, nobs=nobs) , I think it will work the way you desire. 没有可重现的示例,我无法进行测试,但是如果您执行tempVector <- data.frame(id=i, nobs=nobs) ,我认为它将按您期望的方式工作。

Or, you can save a few lines of code and do: 或者,您可以保存几行代码并执行以下操作:

  mydata <- read.csv(files[i])
  output <- rbind(output, data.frame(id=i, nobs=nrow(na.omit(mydata))))

If i am correct you just want to know the id and the number of observations within this id. 如果我是正确的,您只想知道ID和此ID中的观测值数量。
Try readLines instead. 请尝试使用readLines

id <- 1:3
files <- list.files()
files_nrow <- function(id){
  c(id=id, nobs= length(readLines(files[id])))
}

data.frame(t(sapply(id,files_nrow)))

Result: 结果:

  id nobs
1  1   12
2  2   8
3  3   13

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

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