如何解决将字符附加到数据框中列的特定位置
我有这样的数据帧
df <- data.frame(
'Week' = c(27,28,29),'date' = c("2019-W (01-Jul)","2019-W (08-Jul)","2019-W (15-Jul)"))
我需要在日期列的 W 之后附加“周”列
expecteddf <- data.frame(
'Week' = c(27,'date' = c("2019-W27 (01-Jul)","2019-W28 (08-Jul)","2019-W29 (15-Jul)"))
如何在R中实现这一目标?
提前谢谢!
解决方法
您可以将paste0
与sub
组合使用,即
paste0(sub(' .*','',df$date),df$Week,sub('.* ',' ',df$date))
#[1] "2019-W27 (01-Jul)" "2019-W28 (08-Jul)" "2019-W29 (15-Jul)"
,
在基数R中,您还可以使用regmatches
+ regexpr
检查解决方案@Darren来详细说明模式(?<=W)
regmatches(df$date,regexpr("(?<=W)",df$date,perl = TRUE)) <- df$Week
df
Week date
1 27 2019-W27 (01-Jul)
2 28 2019-W28 (08-Jul)
3 29 2019-W29 (15-Jul)
,
使用stringr::str_replace
,可以将替换向量化:
library(stringr)
df$date = str_replace(df$date,"W",paste0("W",df$Week))
df
# Week date
# 1 27 2019-W27 (01-Jul)
# 2 28 2019-W28 (08-Jul)
# 3 29 2019-W29 (15-Jul)
或者,我们可以采用日期格式化方法。将您的date
列转换为实际的Date
类(下面为df$Date
),然后我们可以将实际的Date
转换为您想要的格式(或其他格式)。>
df$Date = as.Date(df$date,format = "%Y-W (%d-%b)")
df$result = format(df$Date,format = "%Y-W%V (%d-%b)")
df
# Week date Date result
# 1 27 2019-W (01-Jul) 2019-07-01 2019-W27 (01-Jul)
# 2 28 2019-W (08-Jul) 2019-07-08 2019-W28 (08-Jul)
# 3 29 2019-W (15-Jul) 2019-07-15 2019-W29 (15-Jul)
,
带有base
的{{1}}解决方案:
sub(...,perl = T)
注意:
-
within(df,date <- Vectorize(sub)("(?<=W)",Week,date,perl = T))
与"(?<=W)"
后面的位置匹配。 -
"W"
的前两个参数不能向量化,因此此处需要sub()
或Vectorize()
。
相应的mapply()
版本已被矢量化。
str_replace()
输出
library(dplyr)
library(stringr)
df %>%
mutate(date = str_replace(date,"(?<=W)",as.character(Week)))
,
使用以下方法的基本R选项:
-
gsub
+Vectorize
expecteddf <- within(df,date <- Vectorize(gsub)("W",Week),date))
-
gsub
+mapply
expecteddf <- within(
df,date <- mapply(function(x,p) gsub("(.*W)(\\s.*)",sprintf("\\1%s\\2",p),x),Week)
)
,
您可以在str_c中使用mutate
library(tidyverse)
df %>%
mutate(date = str_c(str_sub(date,1,6),str_sub(date,7)))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。