简体   繁体   English

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

[英]How to format R data.frame output?

Let me start by saying I am brand new to R, so any solution with a detailed explanation would be appreciated so I can learn from it. 首先,我是R的新手,任何带有详细解释的解决方案都将受到赞赏,以便我可以从中学习。

I have a set of csv files with the following rows of information: 我有一组具有以下信息行的csv文件:

"ID" "Date" "A" "B" (where A and B are some data points) “ ID”,“日期”,“ A”,“ B”(其中A和B是一些数据点)

I am attempting to get the output in a meaningful manner and am stuck on what I am missing. 我试图以有意义的方式获得输出,并坚持我所缺少的。

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

My current output is : 我当前的输出是:

2    4    8   10  12
1000 500 200 150 100

which is correct but I need it in column form so it can be understood by looking at it. 正确,但是我需要以列的形式使用它,以便通过查看可以理解它。 The output I am trying to get to is below: 我试图获得的输出如下:

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

What am I missing here? 我在这里想念什么?

table outputs a contingency table. table输出列联表。 You want a data frame. 您需要一个数据框。 You can wrap as.data.frame(...) around you output to convert it. 您可以将as.data.frame(...)包装在输出周围以对其进行转换。

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

Assuming that the numbers are correct, looks like you have everything you need, just transpose the data frame. 假设数字是正确的,则看起来您已拥有所需的一切,只需转置数据框即可。 Try this: 尝试这个:

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

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

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