从 Dataframe 为多个选定列创建百分比 Table
Create Percentage Table from Dataframe for Multiple Selected Columns
我有一个如下所示的数据框:
COLA COLB COLC COLD COLE
Name1 yes A AB uno
Name2 yes B AC dos
Name3 no C AB tres
Name4 no D AC cuatro
如何创建显示每个选定列值的百分比以及频率的比例数据框:
ATTRIBUTE Percentages Frequency
*COLB* *Percentage* *Amount*
yes 50% 2
no 50% 2
*COLC* *Percentage *Amount*
A 25% 1
B 25% 1
C 25% 1
D 25% 1
*COLD* *Percentage* *Amount*
AB 50% 2
AC 50% 2
它不需要看起来完全像这样,但我需要它全部在一个数据框中并且只包含提到的选定列。
任何帮助都会很棒,谢谢!
您可以执行以下操作:
dat <- data.frame(COLA=paste0("name",1:4),
"COLB"=c("yes", "yes", "no", "no"))
require(purrr)
col_to_stat <- function(col){
tmp <- table(col)
data.frame(ATTRIBUTE = names(tmp), Percentages = c(tmp/length(col)), Frequency = c(tmp),
stringsAsFactors = FALSE)
}
map_df(dat, col_to_stat, .id="col")
这给你:
col ATTRIBUTE Percentages Frequency
1 COLA name1 0.25 1
2 COLA name2 0.25 1
3 COLA name3 0.25 1
4 COLA name4 0.25 1
5 COLB no 0.50 2
6 COLB yes 0.50 2
如果您想打印百分比而不是小数,请查看:
How to format a number as percentage in R?
P.S.: 如果你使用 tibble
而不是 data.frame
你可以使用以下更短的:
tibble(ATTRIBUTE = names(tmp), Percentages = tmp/length(col), Frequency = tmp)
我有一个如下所示的数据框:
COLA COLB COLC COLD COLE
Name1 yes A AB uno
Name2 yes B AC dos
Name3 no C AB tres
Name4 no D AC cuatro
如何创建显示每个选定列值的百分比以及频率的比例数据框:
ATTRIBUTE Percentages Frequency
*COLB* *Percentage* *Amount*
yes 50% 2
no 50% 2
*COLC* *Percentage *Amount*
A 25% 1
B 25% 1
C 25% 1
D 25% 1
*COLD* *Percentage* *Amount*
AB 50% 2
AC 50% 2
它不需要看起来完全像这样,但我需要它全部在一个数据框中并且只包含提到的选定列。
任何帮助都会很棒,谢谢!
您可以执行以下操作:
dat <- data.frame(COLA=paste0("name",1:4),
"COLB"=c("yes", "yes", "no", "no"))
require(purrr)
col_to_stat <- function(col){
tmp <- table(col)
data.frame(ATTRIBUTE = names(tmp), Percentages = c(tmp/length(col)), Frequency = c(tmp),
stringsAsFactors = FALSE)
}
map_df(dat, col_to_stat, .id="col")
这给你:
col ATTRIBUTE Percentages Frequency
1 COLA name1 0.25 1
2 COLA name2 0.25 1
3 COLA name3 0.25 1
4 COLA name4 0.25 1
5 COLB no 0.50 2
6 COLB yes 0.50 2
如果您想打印百分比而不是小数,请查看: How to format a number as percentage in R?
P.S.: 如果你使用 tibble
而不是 data.frame
你可以使用以下更短的:
tibble(ATTRIBUTE = names(tmp), Percentages = tmp/length(col), Frequency = tmp)