合并或c*R在数据框中查找表结果列表(&R);添加缺少的值
我的谷歌技术今天没有成功,所以我问了一个新问题: 我有一个值矩阵合并或c*R在数据框中查找表结果列表(&R);添加缺少的值,r,list,merge,R,List,Merge,我的谷歌技术今天没有成功,所以我问了一个新问题: 我有一个值矩阵c(0,2,3): 我使用apply res <- apply(a, 1, table) res[1:3] [[1]] 2 3 6 4 [[2]] 2 3 6 4 [[3]] 0 2 2 8 和数据: structure(list(`1` = c(2, 2, 0, 0, 2, 2, 2, 2, 2, 2), `2` = c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2), `3` = c(
c(0,2,3)
:
我使用apply
res <- apply(a, 1, table)
res[1:3]
[[1]]
2 3
6 4
[[2]]
2 3
6 4
[[3]]
0 2
2 8
和数据:
structure(list(`1` = c(2, 2, 0, 0, 2, 2, 2, 2, 2, 2), `2` = c(2,
2, 2, 2, 2, 2, 2, 2, 2, 2), `3` = c(2, 2, 2, 2, 2, 2, 2, 2, 2,
2), `4` = c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2), `5` = c(3, 3, 2, 2,
3, 2, 2, 2, 3, 2), `6` = c(3, 3, 2, 2, 3, 2, 2, 2, 3, 2), `7` = c(3,
3, 2, 2, 3, 2, 2, 2, 3, 2), `8` = c(3, 3, 2, 2, 3, 2, 2, 2, 3,
2), `9` = c(2, 2, 0, 0, 2, 2, 2, 2, 2, 2), `10` = c(2, 2, 2,
2, 2, 2, 2, 2, 2, 2)), row.names = c(NA, -10L), class = "data.frame", .Names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10"))
您可以使用
gtools
软件包中的smartbind
:
library(gtools)
do.call(smartbind, c(apply(a, 1, table), fill = 0)) # fill by 0's, default is NA
# 2 3 0
#1 6 4 0
#2 6 4 0
#3 8 0 2
#4 ...
另一种选择是在调用表之前定义完整级别:
res <- apply(a, 1, function(x){x<-factor(x ,levels=c(0,2,3)) ; table(x) } )
as.data.frame(t(res))
# 0 2 3
#[1,] 0 6 4
#[2,] 0 6 4
#[3,] 2 8 0
res这里是另一个使用base R的选项
table(rep(1:nrow(a), ncol(a)), unlist(a))
# 0 2 3
# 1 0 6 4
# 2 0 6 4
# 3 2 8 0
# 4 2 8 0
# 5 0 6 4
# 6 0 10 0
# 7 0 10 0
# 8 0 10 0
# 9 0 6 4
# 10 0 10 0
谢谢。到目前为止,你还没有完成这个函数。我想你应该把它存储为一个矩阵。然后您可以只使用表(行(a),如.matrix(a))
@Frank是迄今为止最优雅的解决方案。竖起大拇指!
res <- apply(a, 1, function(x){x<-factor(x ,levels=c(0,2,3)) ; table(x) } )
as.data.frame(t(res))
# 0 2 3
#[1,] 0 6 4
#[2,] 0 6 4
#[3,] 2 8 0
table(rep(1:nrow(a), ncol(a)), unlist(a))
# 0 2 3
# 1 0 6 4
# 2 0 6 4
# 3 2 8 0
# 4 2 8 0
# 5 0 6 4
# 6 0 10 0
# 7 0 10 0
# 8 0 10 0
# 9 0 6 4
# 10 0 10 0