gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:34:55 24 4
gpt4 key购买 nike

我想使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com