如何根据R中时间变量的范围在数据框中重复行? [英] How to repeat rows in dataframe based on the range of a time variable in R?

查看:42
本文介绍了如何根据R中时间变量的范围在数据框中重复行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 df,所以一行看起来像:

I have a df, such that a row looks like:

name datesemployed        university   
Kate Oct 2015 – Jan 2016  Princeton

我想要做的是在变量 datespaid 的范围内重复每一年的整行.

What I want to do is repeat the entire row for each year in the range of variable datesemployed.

在这种情况下,将有两行 --- 一行是 2015 年,另一行是 2016 年.

In this case, there would be two rows --- one for 2015, and one for 2016.

我曾尝试先清理变量,但即使在如何做到这一点上也遇到了困难:

I've attempted to clean the variable first, but even having a tough time on how to do that:

df3<-str_split_fixed(df$datesemployed, "–", 2)
df<-cbind(df3, df)

推荐答案

我们可以使用 tidyr 中的 separate_rows 同时将 sep 指定为零或多个空格后跟 - 和任何空格

We can use separate_rows from tidyr while specifying the sep as zero or more spaces followed by - and then any spaces

library(dplyr)
library(tidyr)
df %>%
     separate_rows(datesemployed,  sep="\\s*–\\s*")
#    name datesemployed university
#1 Kate      Oct 2015  Princeton
#2 Kate      Jan 2016  Princeton

数据

df <- structure(list(name = "Kate", datesemployed = "Oct 2015 – Jan 2016", 
    university = "Princeton"), class = "data.frame", row.names = c(NA, 
-1L))

这篇关于如何根据R中时间变量的范围在数据框中重复行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆