我有一个数据框,其中显示了许多进行了健康和安全测试的商店。在这个数据框中,我有商店的名称和一个显示某一天的测试结果的因子。
head(facttab)
new_table.dba_name new_table.results
1 QUICK SUB Out of Business
2 BAR BARI Pass
3 FOOD FIRST CHICAGO Pass
4 TRATTORIA ISABELLA Pass
5 DELI-TIME, L.L.C. Pass
6 GREAT AMERICAN BAGEL Fail
>
facttab <- data.frame(new_table$dba_name, new_table$results)
head(table(facttab))
new_table.dba_name Fail No Entry Not Ready Out of Business Pass Pass w/ Conditions
1 2 3 EXPRESS 1 0 0 0 0 0
1155 CAFETERIA 0 0 0 0 1 0
16TH ST FOOD MART 0 0 0 1 0 0
194 RIB JOYNT 0 1 0 0 0 0
24HR MINI MART & CELLAR FOR YOU 1 0 0 0 0 0
7-ELEVEN 0 0 0 0 4 2我想构建另一个表或数据框架,显示整个数据框架中每个商店测试的总结果的百分比,这样我就可以看到谁有最大的%失败和最大的%通过。
结果表将类似于上面的示例7-11将是- 0%,无条目- 0%,未就绪出- 0%,出业务0%,通过- 66%和通过w/条件- 33%。
发布于 2016-05-08 22:13:16
我想我会想出一个答案的。这是如何将prop.table转换为data.frame的方法。我相信可能有一种更快的方法来做这件事。请注意,我使用的是自己创建的数据集。了解一下?reshape可能会有所帮助
set.seed(123)
#create some dummy data
df <- data.frame(store = sample(c('a','b','c'), 100, replace = T),
status = sample(c('foo','bar','haz'), 100, replace = T))
#convert to prop.table
(prop.t <- prop.table(table(df$store, df$status), 1))
bar foo haz
a 0.4242424 0.2121212 0.3636364
b 0.4117647 0.4117647 0.1764706
c 0.3636364 0.3030303 0.3333333
#coerce to data.frame
(prop.t.df <- data.frame(prop.t))
Var1 Var2 Freq
1 a bar 0.4242424
2 b bar 0.4117647
3 c bar 0.3636364
4 a foo 0.2121212
5 b foo 0.4117647
6 c foo 0.3030303
7 a haz 0.3636364
8 b haz 0.1764706
9 c haz 0.3333333
#use reshape()
(reshape(prop.t.df, direction = 'wide', idvar = 'Var1', v.names = 'Freq', timevar = 'Var2'))
Var1 Freq.bar Freq.foo Freq.haz
1 a 0.4242424 0.2121212 0.3636364
2 b 0.4117647 0.4117647 0.1764706
3 c 0.3636364 0.3030303 0.3333333显然,您可能希望稍微玩弄一下名称,但这是获得您想要的内容的一种方法。
PS另一种方法是:
prop.t.df2 = as.data.frame.matrix(prop.t)注意:您可能需要通过访问Store的row.names来创建一个名为prop.t.df2的新列。
prop.t.df2$Store = row.names(prop.t.df2)https://stackoverflow.com/questions/37086505
复制相似问题