Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R dplyr: Use the function as a string in one column on the next column

Tags:

r

dplyr

lubridate

I want to apply a function, which name is stored in a column as a string, on a value in another column, using dplyr. I have tried several things using mutate_ and a .dots argument, but I am stuck now.

library(lubridate)
library(dplyr)

df <- data.frame(date=as.POSIXct('2017/01/01 12:34') + 1:10*123456,
                 fun=rep(c('minute','hour','day','month','year'),2))

input:

> df
                  date    fun
1  2017-01-02 22:51:36 minute
2  2017-01-04 09:09:12   hour
3  2017-01-05 19:26:48    day
4  2017-01-07 05:44:24  month
5  2017-01-08 16:02:00   year
6  2017-01-10 02:19:36 minute
7  2017-01-11 12:37:12   hour
8  2017-01-12 22:54:48    day
9  2017-01-14 09:12:24  month
10 2017-01-15 19:30:00   year

output:

                  date    fun  res
1  2017-01-02 22:51:36 minute   51
2  2017-01-04 09:09:12   hour    9
3  2017-01-05 19:26:48    day    5
4  2017-01-07 05:44:24  month    1
5  2017-01-08 16:02:00   year 2017
6  2017-01-10 02:19:36 minute   19
7  2017-01-11 12:37:12   hour   12
8  2017-01-12 22:54:48    day   12
9  2017-01-14 09:12:24  month    1
10 2017-01-15 19:30:00   year 2017
like image 618
Wietze314 Avatar asked Jan 24 '26 16:01

Wietze314


1 Answers

One way , I could think of is using creating a lookup table and then getting the correct output format using match

x <- c("minute", "hour", "day", "month", "year")
y <- c("%M", "%H", "%d", "%m", "%Y")

format(df$date, format = y[match(df$fun, x)])
#[1] "51"   "09"   "05"   "01"   "2017" "19"   "12"   "12"   "01"   "2017"

Although, this gives a warning message but still the output is correct.

If we need this in a dplyr chain

library(dplyr)
df %>%
  mutate(res = format(date, format = y[match(df$fun, x)])) 


#                 date    fun   res
#1  2017-01-02 22:51:36 minute   51
#2  2017-01-04 09:09:12   hour   09
#3  2017-01-05 19:26:48    day   05
#4  2017-01-07 05:44:24  month   01
#5  2017-01-08 16:02:00   year 2017
#6  2017-01-10 02:19:36 minute   19
#7  2017-01-11 12:37:12   hour   12
#8  2017-01-12 22:54:48    day   12
#9  2017-01-14 09:12:24  month   01
#10 2017-01-15 19:30:00   year 2017
like image 103
Ronak Shah Avatar answered Jan 27 '26 07:01

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!