简体   繁体   中英

Turning numeric column to year and month duration in r

This is a part of my df, which represents relationship duration:

   r_duration_1 r_duration_2
3             0            4
4             1            4
5             2            4
6             0            9
7             1            3
8             5            0
9             0            9
10            0           11

duration_1 represents years and duration_2 represents months. How can I turn these columns from numeric to a duration that I can do operations on it like mean relationship duration and so on?

You can keep the data as it is. Average relationship duration in months can be calculated as:

mean(with(df, r_duration_1 * 12 + r_duration_2))

We can use rowSums after multiplying with different weights and get the mean

mean(rowSums(df * c(12, 1)[col(df)]))  

Or using Map/Reduce

mean(Reduce(`+`, Map(`*`, df, c(12, 1))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM