我有一个数据:
df_1 <- data.frame(
cpf = c('37576865879', '02177190948')
)
我尝试:
library(tidyverse)
str_sub(string = df_1$cpf, start = 4, end = 6) <- 'xxx'
# cpf
#1 375xxx65879
#2 021xxx90948
结果正常。但是:
df_1 <- data.frame(
cpf = c('37576865879', '02177190948')
)
df_1 %>%
mutate(.data = ., var = str_sub(string = cpf, start = 4, end = 6) <- "xxx")
# cpf var
#1 37576865879 xxx
#2 02177190948 xxx
仅x
出现在var
中。如何调整最后一个函数以获得完整的向量?
# cpf var
#1 37576865879 375xxx65879
#2 02177190948 021xxx90948
答案 0 :(得分:1)
要在管道中使用此方法,必须使用str_sub<-
方法,该方法可以用作:
library(dplyr)
library(stringr)
df_1 %>% mutate(var = `str_sub<-`(cpf, 4, 6, value = 'xxx'))
# cpf var
#1 37576865879 375xxx65879
#2 02177190948 021xxx90948