检查一个变量R内的各种DATE的差异

ran*_*ane 7 r date list unnest mutate

我想在变量包含不同的YEAR时拆分行,也拆分col:"Price"用均匀的除以日期的数字 - > count(";")+1

有一个表尚未拆分变量.

# Dataset call df 

Price   Date 
500     2016-01-01
400     2016-01-03;2016-01-09
1000    2016-01-04;2017-09-01;2017-08-10;2018-01-01
25      2016-01-04;2017-09-01
304     2015-01-02
238     2018-01-02;2018-02-02
Run Code Online (Sandbox Code Playgroud)

欲望展望

# Targeted df
Price   Date 
500     2016-01-01
400     2016-01-03;2016-01-09
250     2016-01-04
250     2017-09-01
250     2017-08-10
250     2018-01-01
12.5    2016-01-04
12.5    2017-09-01
304     2015-01-02
238     2018-01-02;2018-02-02
Run Code Online (Sandbox Code Playgroud)

一旦变量包含不同的年份定义,下面是操作必须做的.(这只是一个例子.)

mutate(Price = ifelse(DIFFERENT_DATE_ROW,
                     as.numeric(Price) / (str_count(Date,";")+1),
                     as.numeric(Price)),
       Date = ifelse(DIFFERENT_DATE_ROW,
                     strsplit(as.character(Date),";"),
                     Date)) %>%
 unnest()
Run Code Online (Sandbox Code Playgroud)

我遇到了一些不能使用dplyr函数的约束,"if_else"因为 否则无法识别NO操作.只有ifelse正常工作.

如何找出一个变量中的年份差异来PROVOKE分割线和拆分价格计算?

到目前为止分裂元素的操作就像

unlist(lapply(unlist(strsplit(df1$noFDate[8],";")),FUN = year))
Run Code Online (Sandbox Code Playgroud)

无法解决问题.

我是编码的初学者,请考虑真实数据超过200万行和50列,请随意更改上述所有操作.

Ron*_*hah 2

这可能不是最有效的方法,但可以用来获得所需的答案。

#Get the row indices which we need to separate
inds <- sapply(strsplit(df$Date, ";"), function(x) 
#Format the date into year and count number of unique values
#Return TRUE if number of unique values is greater than 1
    length(unique(format(as.Date(x), "%Y"))) > 1
)

library(tidyverse)
library(stringr)

#Select those indices 
df[inds, ] %>%
   # divide the price by number of dates in that row 
    mutate(Price = Price / (str_count(Date,";") + 1)) %>%
   # separate `;` delimited values in separate rows
    separate_rows(Date, sep = ";") %>%
   # bind the remaining rows as it is 
    bind_rows(df[!inds,])


# Price                  Date
#1  250.0            2016-01-04
#2  250.0            2017-09-01
#3  250.0            2017-08-10
#4  250.0            2018-01-01
#5   12.5            2016-01-04
#6   12.5            2017-09-01
#7  500.0            2016-01-01
#8  400.0 2016-01-03;2016-01-09
#9  304.0            2015-01-02
#10 238.0 2018-01-02;2018-02-02
Run Code Online (Sandbox Code Playgroud)