如何格式化R data.frame输出?

时间:2016-02-25 20:03:58

标签: r dataframe

首先让我说我是R的新手,所以任何有详细解释的解决方案都会受到赞赏,所以我可以从中学习。

我有一组包含以下信息行的csv文件:

" ID" "日期" " A" " B" (其中A和B是一些数据点)

我试图以有意义的方式获得输出,而且我仍然坚持我所缺少的东西。

observations <- funtion(dir, id= 1:10){
  #get all file names in a vector
  all_files <- list.files(directory, full.names=TRUE)
  #get the subset of files we want to read
  file_contents <- lapply(all_files[id], read.csv)
  #cbind the file contents
  output <- do.call(rbind, file_contents)
  #remove all NA values
  output <- output[complete.cases(output), ]

  #at this point output is a data.frame so display the output
  table(output[["ID"]])
}

我目前的输出是:

2    4    8   10  12
1000 500 200 150 100

这是正确的,但我需要它以列形式,所以通过查看它可以理解。我想要的输出如下:

   id obs_total
 1  2 1000
 2  4  500
 3  8  200
 4 10  150
 5 12  100

我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

table输出列联表。你想要一个数据框。您可以在输出周围包裹as.data.frame(...)以进行转换。

as.data.frame(table(ID = output[["ID"]]))

答案 1 :(得分:0)

假设数字是正确的,看起来你拥有所需的一切,只需转置数据框。试试这个:

mat<-matrix(round(runif(10),3),nrow=2)
df<-as.data.frame(mat)
colnames(df)=c("1","2","3","4","5")
t(df)