如何计算R中2列之间的比率(使用函数)?
我们正在进行一个实验,以检查品牌对产品价值的影响。 为了计算结果,我们首先需要计算2个答案之间的比率。 我们想通过功能而不是手动来执行此操作。 例如
prod1_nobrand prod1_brand prod2_nobrand prod2_brand
1 2 4 8
2 6 5 20
我们要为每个比率创建一个新列 例如,
prod1_ratio prod2_ratio
2 2
3 4
任何想法如何做? 谢谢你!
we are running an experiment that checks the effect of brand on product value.
In order to calculate the results, we first need to calculate the ratio between 2 answers to the same product.
We want to do it by a function and not manual.
for example
prod1_nobrand prod1_brand prod2_nobrand prod2_brand
1 2 4 8
2 6 5 20
we want to create a new column for each ratio
for example
prod1_ratio prod2_ratio
2 2
3 4
any idea how to do that?
thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简单的基础方法将如下...
The simple base R way to do that would be as follows...
我不是100%确定我正确理解您的问。但是我的感觉是您应该熟悉
dplyr
功能。您可以使用突变
函数以这种方式创建新列:I'm not 100% sure I'm understanding your ask correctly. But my feeling is that you should familiarize yourself with
dplyr
functions. You can use themutate
function to create new columns in this way:一个选项是将其置于长形式,计算比率,然后使用
tidyverse
旋转到宽形式。输出
数据
One option is the put it into long form, calculate the ratio, then pivot back to wide form with
tidyverse
.Output
Data
如果在给定的示例
c(false,true)
和c(true,false)
中,可以使用列与列配对。数据:
In case the columns are paired like in the given example
c(FALSE, TRUE)
andc(TRUE, FALSE)
could be used to subset and make the division.Data: