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

标签 r dplyr lubridate

我想使用 dplyr 将名称作为字符串存储在一列中的函数应用于另一列中的值。 我已经使用 mutate_.dots 参数尝试了几件事,但我现在卡住了。

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))

输入:

> 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

输出:

                  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

最佳答案

我能想到的一种方法是使用创建查找表,然后使用 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"

尽管这给出了警告消息,但输出仍然是正确的。

如果我们在 dplyr 链中需要这个

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

关于R dplyr : Use the function as a string in one column on the next column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41976018/

相关文章:

r - 避免 dplyr 中向量和变量名之间的冲突

r - 如何从R中的日期中提取月和日并将其转换为日期类型?

r - 如何将数据列表保存到 R 中的文本文件?

r - 如何在控制台模式下删除R的启动消息?

r - 如何在太多循环中加速应用函数

r - 为什么过滤到 ggplot() 中的数据集样本会返回不正确的样本?

根据条件重新排序变量

r - 在 R 中计算省略重叠日期的持续时间

r - 如何从日期获得下周日结束的一周

R 数据表 : Hide search box for individual columns