【问题标题】:Do.Call, Rbind dataframe - add column name, and long to wide dataDo.Call,Rbind 数据框 - 添加列名和长到宽数据
【发布时间】:2016-08-29 07:20:59
【问题描述】:

我正在分析 200 个 csv 文件中的数据。我已经在 R 中导入了文件,并创建了几个不同的函数,以便结果能够为我提供每个文件的函数(按颜色计数和求和)结果。函数结果采用数据框的形式。
对于最终结果,我使用了 do.call(rbind,result) 的组合,它产生如下输出: 因为我使用的是 rbind,所以第一列没有标题。

          Count Sum
File1.Blue  5   10
File1.Red   2   6
File2.Blue  1   3
File2.Red   1   1
File3.Blue  4
File3.Red   7   2   

列表很长。我想转置结果,使最终结果看起来像:

       Blue Count Blue Sum  Red Count   Red Sum
File 1      5       10      2       6
File 2      1       3       1       1
File 3      4       0       7       2

我想我需要使用 reshape 或 cast 功能......但我不知道如何先拆分文件名然后排列数据

【问题讨论】:

  • 您需要正确格式化您的问题。现在不可读了。

标签: r


【解决方案1】:

我们可以从data.table 使用dcast。通过拆分原始数据集的行名,在原始数据集中创建两个新列(或通过cbinding 将新列与原始数据集作为新数据集)。然后,将 'data.frame' 转换为 'data.table' (setDT(df2)),并使用dcast,它可以占用多个value.var 列。

library(data.table)
 df2 <- cbind(read.table(text=row.names(df1), sep=".",
  header=FALSE, stringsAsFactors=FALSE), `row.names<-`(df1[,1:2], NULL))
dcast(setDT(df2), V1~V2, value.var= c("Count", "Sum"))
#       V1 Count_Blue Count_Red Sum_Blue Sum_Red
#1: File1          5         2       10       6
#2: File2          1         1        3       1
#3: File3          4         7       NA       2

数据

 df1 <- structure(list(Count = c(5L, 2L, 1L, 1L, 4L, 7L), Sum = c(10L,  
 6L, 3L, 1L, NA, 2L)), .Names = c("Count", "Sum"), class = "data.frame", 
 row.names = c("File1.Blue", 
 "File1.Red", "File2.Blue", "File2.Red", "File3.Blue", "File3.Red"))

【讨论】:

  • 这行得通!非常感谢。你能帮我理解 cbind 函数中发生了什么吗? text=row.names(df1) 如何知道只拆分第一列?第二个命令 - row.names&lt;-(df1[,1:2], NULL) - 为什么用引号括起来?再次感谢您。
猜你喜欢
  • 2019-11-03
  • 2023-03-05
  • 1970-01-01
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多