apply() 并计算所有数据帧行的第一行的比例 [英] apply() and calculating proportion of first row for all dataframe rows

查看:26
本文介绍了apply() 并计算所有数据帧行的第一行的比例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,如下所示,按车辆类型列出了受伤人数:

I have a dataframe as shown below listing the number of injuries by vehicle type:

trqldnum <- data.frame(motorveh=c(796,912,908,880,941,966,989,984),
                       motorcyc=c(257,295,326,313,403,389,474,496),
                       bicyc=c(109,127,125,137,172,146,173,178))
trqldnum

#  motorveh motorcyc bicyc
#1      796      257   109
#2      912      295   127
#3      908      326   125
#4      880      313   137
#5      941      403   172
#6      966      389   146
#7      989      474   173
#8      984      496   178

目前我正在计算每种车辆类型第一行的比例:

At the moment I am calculating a proportion of the first row for each vehicle type using:

trqldprop <- t(apply(trqldnum,1,function(x) {
                 x/c(trqldnum[1,1],trqldnum[1,2],trqldnum[1,3])
              }))
trqldprop

#  motorveh motorcyc    bicyc
#1 1.000000 1.000000 1.000000
#2 1.145729 1.147860 1.165138
#3 1.140704 1.268482 1.146789
#4 1.105528 1.217899 1.256881
#5 1.182161 1.568093 1.577982
#6 1.213568 1.513619 1.339450
#7 1.242462 1.844358 1.587156
#8 1.236181 1.929961 1.633028

这看起来有点难看,如果数据改变形状,我需要手动更改函数的分母.如果我尝试只在 apply() 语句中使用以下内容,我最终会得到一个列表列表中的输出.

This seems a bit ugly and I would need to manually change the denominator of the function if the data changed shape. I end up with the output in a list of a lists if I try to just use the following within the apply() statement.

function(x) x/c(trqldnum[1,])

我更愿意以上述数据帧结果结束,但我只是在试图弄清楚它时陷入困境.

I'd prefer to end up with the dataframe result as above but am just getting in a muddle trying to figure it out.

推荐答案

怎么样

sweep(trqldnum,2,unlist(trqldnum[1,]),"/")

?

unlist 需要将数据框的第一行转换成可以扫过的向量...

The unlist is required to convert the first row of the data frame into a vector that can be swept ...

这篇关于apply() 并计算所有数据帧行的第一行的比例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆