0
$\begingroup$

i have a data frame

 > data
session id        item id 
  1                 1 
  1                 1
  1                 1
  2                 1
  2                 2
  3                 1
  3                 0
  3                 3
  3                 2

and i want to calculate avg of each session id like this uniqueitemsinsession/totalitems= ans (1/3=0.333)and get result like this

>  result   
session id       avg
   1             0.333
   2             1.000
   3             1.000

how can i do this??

$\endgroup$

2 Answers 2

0
$\begingroup$

Assuming you can use dplyr package

data %>% group_by(session_id) %>% summarise(avg = length(unique(item_id))/length(item_id))

You have asked many questions on basic grouping and summarise operations in R. It would be better to go through tutorials like this to learn all these tricks in one go.

$\endgroup$
0
0
$\begingroup$

Try aggregating your dataframe on the session id column against the item id column - and pass the function you want, namely mean:

newDF <- aggregate(`item id` ~ `session id`, data, mean)

Those backticks should be necessary as your column names contain spaces.

Here are some other alternative methods to get the job done.

–––

You could rename them using this:

names(data) <- c("col1", "col2") 
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.