R 频率表:如果变量中的所有数据点共享结果,prop.table 不起作用?
R Frequency Tables: prop.table does not work if all data points within variable share the outcome?
想象一下,您有以下数据集:
df<-data.frame(read.table(header = TRUE, text = "
ID Wine Beer Water Age Gender
1 0 1 0 20 Male
2 1 0 1 38 Female
3 0 0 1 32 Female
4 1 0 1 30 Male
5 1 1 1 30 Male
6 1 1 1 26 Female
7 0 1 1 36 Female
8 0 1 1 29 Male
9 0 1 1 33 Female
10 0 1 1 20 Female"))
此外,假设您想编制汇总表,打印出饮用葡萄酒、啤酒和水的频率。
我就是这样解决的。
con<-apply(df[,c(2:4)], 2, table)
con_P<-prop.table(con,2)
效果很好。没问题。现在,让我们按如下方式调整数据集:我们将水的所有条目设置为 1
.
df<-data.frame(read.table(header = TRUE, text = "
df<-data.frame(read.table(header = TRUE, text = "
ID Wine Beer Water Age Gender
1 0 1 1 20 Male
2 1 0 1 38 Female
3 0 0 1 32 Female
4 1 0 1 30 Male
5 1 1 1 30 Male
6 1 1 1 26 Female
7 0 1 1 36 Female
8 0 1 1 29 Male
9 0 1 1 33 Female
10 0 1 1 20 Female"))
如果我现在运行以下命令:
con<-apply(df[,c(2:4)], 2, table)
con_P<-prop.table(con,2)
它在第二行之后给我以下错误消息:Error in margin.table(x, margin) : 'x' is not an array
!为什么?
如果一个变量中的所有数据点都具有相同的结果,为什么会有所不同?另外,我该怎么做才能避免这个问题?谢谢大家!
函数prop.table
使用了函数sweep
,它接受一个数组作为第一个参数。由于您的第二个 con
是列表而不是数组,因此 prop.table
将失败。
为什么你的第二个 con
是列表?因为 Water
列只有一个元素,而所有其他列都有 2 个元素。当元素个数不同时apply
无法将结果简化为数组,给你一个列表。
在您给我们的示例中,更安全的方法是使用 lapply
,它总是会给出一个包含结果的列表:
con <- lapply(df, table)
con_P <- lapply(con, function(x) x/sum(x))
想象一下,您有以下数据集:
df<-data.frame(read.table(header = TRUE, text = "
ID Wine Beer Water Age Gender
1 0 1 0 20 Male
2 1 0 1 38 Female
3 0 0 1 32 Female
4 1 0 1 30 Male
5 1 1 1 30 Male
6 1 1 1 26 Female
7 0 1 1 36 Female
8 0 1 1 29 Male
9 0 1 1 33 Female
10 0 1 1 20 Female"))
此外,假设您想编制汇总表,打印出饮用葡萄酒、啤酒和水的频率。
我就是这样解决的。
con<-apply(df[,c(2:4)], 2, table)
con_P<-prop.table(con,2)
效果很好。没问题。现在,让我们按如下方式调整数据集:我们将水的所有条目设置为 1
.
df<-data.frame(read.table(header = TRUE, text = "
df<-data.frame(read.table(header = TRUE, text = "
ID Wine Beer Water Age Gender
1 0 1 1 20 Male
2 1 0 1 38 Female
3 0 0 1 32 Female
4 1 0 1 30 Male
5 1 1 1 30 Male
6 1 1 1 26 Female
7 0 1 1 36 Female
8 0 1 1 29 Male
9 0 1 1 33 Female
10 0 1 1 20 Female"))
如果我现在运行以下命令:
con<-apply(df[,c(2:4)], 2, table)
con_P<-prop.table(con,2)
它在第二行之后给我以下错误消息:Error in margin.table(x, margin) : 'x' is not an array
!为什么?
如果一个变量中的所有数据点都具有相同的结果,为什么会有所不同?另外,我该怎么做才能避免这个问题?谢谢大家!
函数prop.table
使用了函数sweep
,它接受一个数组作为第一个参数。由于您的第二个 con
是列表而不是数组,因此 prop.table
将失败。
为什么你的第二个 con
是列表?因为 Water
列只有一个元素,而所有其他列都有 2 个元素。当元素个数不同时apply
无法将结果简化为数组,给你一个列表。
在您给我们的示例中,更安全的方法是使用 lapply
,它总是会给出一个包含结果的列表:
con <- lapply(df, table)
con_P <- lapply(con, function(x) x/sum(x))