如何将数据框中的列制表并将结果放入单个数据框中
How to tabulate columns in a data frame and put the results in a single data frame
我有一个400行1200列的数据框,大体结构是这样的:
> df=data.frame(Col1=paste0('row',1:15),metric1=sample(c('H','M','L'),15,replace = 1),metric2=sample(c('H','M'),15,replace = 1))
> df
Col1 metric1 metric2 ...
1 row1 M H
2 row2 H L
我想做的是根据每列的 HML 计数比较每行的表格结果。
我试过了
> apply(df[,2:3],2,function(x) table(x))
$metric1
x
H L M
1 7 7
$metric2
x
H M
10 5
>
但结果是 1200 的列表,因为并非所有列都包含所有 3 个值,即一列只有 HL,而另一列将有 HML。
我也试过聚合,结果报错
> apply(df[,2:3],2,function(x) aggregate(df$count,list(df[,x]),sum))
Error in `[.data.frame`(df, , x) : undefined columns selected
但我的功能有效:
> aggregate(df$count,list(df[,2]),sum)
Group.1 x
1 H 1
2 L 7
3 M 7
>
我希望将其保存为数据框,例如:
> data.frame(var=c('H','M','L'),metric1=c(100,100,200),metric2=c(250,150,0))
var metric1 metric2
1 H 100 250
2 M 100 150
3 L 200 0
>
我会首先将指标转换为具有 H、L、M 水平的因素,以确保所有 table
都归为 3 个类别。
这导致:
df=data.frame(Col1=paste0('row',1:15),metric1=sample(c('H','M','L'),15,replace = 1),metric2=sample(c('H','M'),15,replace = 1))
for (i in 2:ncol(df)){
df[[i]] <- factor(df[[i]],levels=c("H","M","L"))
}
然后随叫随到,在每个列和堆栈上应用 table:
sapply(df[-1],table)
metric1 metric2
H 3 8
M 1 7
L 11 0
或者,您可以执行以下操作:
sumer <- function(data, pattern)
{
temp <- colSums(sapply(pattern, grepl, data))
names(temp) <- pattern
temp
}
apply(df[, 2:3], 2, sumer, unique(df[, 2]))
或者如果你不想使用循环,你也可以在table函数中分配级别:
apply(df[,2:3],2,function(x) table(factor(x,levels=c("H","M","L"))))
metric1 metric2
H 6 11
M 8 4
L 1 0
我有一个400行1200列的数据框,大体结构是这样的:
> df=data.frame(Col1=paste0('row',1:15),metric1=sample(c('H','M','L'),15,replace = 1),metric2=sample(c('H','M'),15,replace = 1))
> df
Col1 metric1 metric2 ...
1 row1 M H
2 row2 H L
我想做的是根据每列的 HML 计数比较每行的表格结果。
我试过了
> apply(df[,2:3],2,function(x) table(x))
$metric1
x
H L M
1 7 7
$metric2
x
H M
10 5
>
但结果是 1200 的列表,因为并非所有列都包含所有 3 个值,即一列只有 HL,而另一列将有 HML。
我也试过聚合,结果报错
> apply(df[,2:3],2,function(x) aggregate(df$count,list(df[,x]),sum))
Error in `[.data.frame`(df, , x) : undefined columns selected
但我的功能有效:
> aggregate(df$count,list(df[,2]),sum)
Group.1 x
1 H 1
2 L 7
3 M 7
>
我希望将其保存为数据框,例如:
> data.frame(var=c('H','M','L'),metric1=c(100,100,200),metric2=c(250,150,0))
var metric1 metric2
1 H 100 250
2 M 100 150
3 L 200 0
>
我会首先将指标转换为具有 H、L、M 水平的因素,以确保所有 table
都归为 3 个类别。
这导致:
df=data.frame(Col1=paste0('row',1:15),metric1=sample(c('H','M','L'),15,replace = 1),metric2=sample(c('H','M'),15,replace = 1))
for (i in 2:ncol(df)){
df[[i]] <- factor(df[[i]],levels=c("H","M","L"))
}
然后随叫随到,在每个列和堆栈上应用 table:
sapply(df[-1],table)
metric1 metric2
H 3 8
M 1 7
L 11 0
或者,您可以执行以下操作:
sumer <- function(data, pattern)
{
temp <- colSums(sapply(pattern, grepl, data))
names(temp) <- pattern
temp
}
apply(df[, 2:3], 2, sumer, unique(df[, 2]))
或者如果你不想使用循环,你也可以在table函数中分配级别:
apply(df[,2:3],2,function(x) table(factor(x,levels=c("H","M","L"))))
metric1 metric2
H 6 11
M 8 4
L 1 0