当前位置: 动力学知识库 > 问答 > 编程问答 >

write a function to add multiple columns with quotient of a division in R

问题描述:

I would like to add a series of columns with the quotient of a division. My dataframe looks like this:

views01 users01 views02 users02

2 4 4 1

4 5 11 2

5 2 9 4

I'd like to write a piece of code that computes the division views(n)/users(n) and adds columns to the df, like so:

 views01 users01 views02 users02 views_per_user01 views_per_user02

2 4 4 1 0.5 4

4 5 11 2 0.8 5.5

5 2 9 4 2.5 2.25

For the time being, I've created a line of code like that:

df$views_per_user01=df$views01/df$users01

df$views_per_user02=df$views02/df$users02

For each of the cases, but I'd like to shrink it to a single line.

Thank you.

网友答案:

One way to do it assuming that your data frame will be sorted as per your example,

cbind(df, sapply(unique(sub('\\D+', '', names(df))), 
                       function(i) Reduce('/', df[,grepl(i, sub('\\D+', '', names(df)))])))

#  views01 users01 views02 users02  01   02
#1       2       4       4       1 0.5 4.00
#2       4       5      11       2 0.8 5.50
#3       5       2       9       4 2.5 2.25
网友答案:

You can use dplyr's mutate function to append the new columns:

library(dplyr) 
mutate(df, views_per_user01=views01/users01,                
           views_per_user02=views02/users02)
分享给朋友:
您可能感兴趣的文章:
随机阅读: