首先,这是一个非常基本的问题,我不确定如何表达。如果问题是重复的(尽管我使用我认为可能合适的措辞进行了检查),我显然会撤回并欣赏该链接。
第二,我是sure有一种更简单的方法可以完成我正在尝试的事情,但又不想偏离轨道。
好的。我试图从 0/1 矩阵中获取列比例表(1 的比例以另一个变量的值为条件,在本例中为 PARTY)。
我的 data.frame 是 m103,尺寸为 (437,91),以下过程有效(如,产生我想要的):
prop.table(as.matrix(ddply(m103, .(PARTY), sum, na.rm=T)))
但当然,我想实际保留输出,这就是错误出现的地方。如果我这样做:
a <- prop.table(as.matrix(ddply(m103, .(PARTY), sum, na.rm=T)))
事情很棒。但在此之后,如果我立即尝试:
m103.avg.prop <- prop.table(as.matrix(ddply(m103, .(PARTY), sum, na.rm=T)))
我收到错误:
Error in FUN(X[[2L]], ...) : only defined on a data frame with all numeric variables
我想在我的代码中保留合理的命名方案(第二个示例将继续),但我无法判断这是否与我尝试将输出分配给的内容有关,或者与其他内容有关。
非常感谢!
编辑:让我们看看我是否可以更明确
#Data import
m103 <- read.csv("103_members_party.csv", header=T)
#See the first few rows/columns
m103[1:5,1:5]
#Produces this:
ID PARTY X930 X461 X137
1 15245 100 0 0 0
2 15000 100 0 0 0
3 29108 200 0 0 0
4 15001 100 0 0 0
5 29132 100 0 0 0
#Sum and get col percentages by PARTY (sums the 1's when PARTY==100, PARTY==200, etc)
#WITHOUT assigning to anything
prop.table(as.matrix(ddply(m103, .(PARTY), sum, na.rm=T)))
#Produces:
PARTY V1
[1,] 1.122515e-05 0.580000465
[2,] 2.245030e-05 0.416619418
[3,] 3.681849e-05 0.003309623
#With assignment to a
a <- prop.table(as.matrix(ddply(m103, .(PARTY), sum, na.rm=T)))
a
#Produces
PARTY V1
[1,] 1.122515e-05 0.580000465
[2,] 2.245030e-05 0.416619418
[3,] 3.681849e-05 0.003309623
#Now, assignment to m103.avg.prop
m103.avg.prop <- prop.table(as.matrix(ddply(m103, .(PARTY), sum, na.rm=T)))
#results in error:
Error in FUN(X[[2L]], ...) :
only defined on a data frame with all numeric variables