r - 在 R 中使用 split() 后将观察结果制成表格的惯用方法
问题描述
有没有一种更惯用的方法来制表观察的数量是每个数据帧都是通过在 R 中的两列上拆分数据帧获得的?很难描述,所以我写了我想做的事。
splittable <- function(data,rowdata,coldata) {
# data is the data frame for all your data
# rowdata is a column from data
# coldata is another column from data
# This function returns a table counting the number of observations
# from splitting the data by the rowdata and coldata values.
splits <- as.data.frame(lapply(split(data,list(rowdata,coldata)),nrow))
rowlevs <- levels(as.factor(rowdata))
numrowlevs <- length(rowlevs)
collevs <- levels(as.factor(coldata))
outtable <- data.frame()
for (i in seq(from=1,to=numrowlevs,by=1)) {
indexes <- seq(from=i,to=length(splits),by=numrowlevs)
tempdf <- as.data.frame(splits[indexes])
names(tempdf) <- collevs
outtable <- rbind(outtable,tempdf)
}
row.names(outtable) <- rowlevs
return(outtable)
}
似乎应该有一个功能可以为我执行此操作,但我找不到它。
解决方案
我想你可能只是重新发明了这个功能table
。让我们检查一下mtcars
:
splittable(mtcars, mtcars$gear, mtcars$carb)
#> 1 2 3 4 6 8
#> 3 3 4 3 5 0 0
#> 4 4 4 0 4 0 0
#> 5 0 2 0 1 1 1
table(mtcars$gear, mtcars$carb)
#>
#> 1 2 3 4 6 8
#> 3 3 4 3 5 0 0
#> 4 4 4 0 4 0 0
#> 5 0 2 0 1 1 1
推荐阅读
- c++ - OpenCV EqualizeHist() 从彩色图像创建黑白图像
- javascript - 使用 DOM 结合 For 循环创建表;用数组填充表?- JavaScript
- c - Makefile 编译所有 .c 文件而不需要指定它们
- javascript - ReactJS fetch 导致无限循环
- algorithm - 我对红色和黑色树的左旋转算法有疑问
- javascript - 如何建立一个新的结构以便基于价值进行分组
- java - Android - Firebase 访问级别
- strapi - Strapi - 无法“添加内容类型”
- java - 按位操作数的初学者解释
- c++ - 调用专用模板时出现错误“没有用于调用 [...] 的匹配函数”