简体   繁体   English

如果满足 R 中的条件,则 Append 或将文本添加到列

[英]Append or add text to a column if meet condition in R

data <- data.frame(x1 = c("2 August 2020", "4 September", "5 December 2020),    
#  Create example data
                   x2 = c(11/14/2020, 2/4/2020, 12/10))

I want to add "2020" and "/2020" to the end of any row that does not have 2020 in their value.我想将“2020”和“/2020”添加到任何没有 2020 值的行的末尾。 So far I tried this and it add '2020' to all the row.到目前为止,我尝试了这个,它在所有行中添加了“2020”。

for (i in 1:nrow(data)){ifelse("2020" %in% data$x1[i], '', data$x1[i] <- paste0(data$x1[i], " 2020"))}

Is there anyway we can skip the row with 2020 in the text/string?无论如何我们可以跳过文本/字符串中带有 2020 的行吗?

We can use grepl to find cases where there are no 4 digit numbers at the end of the string in each column and paste those elements with 2020我们可以使用grepl查找每列字符串末尾没有 4 位数字的情况,并将这些元素paste2020

data[] <- lapply(data, function(x) 
      ifelse(!grepl("\\d{4}$", x), paste0(x, "/2020"), x))

Another option would be to convert to Date class with anydate and then set the year to 2020另一种选择是使用 anydate 转换为Date anydate然后将year设置为 2020

library(dplyr)
library(anytime)
library(lubridate)
data %>%
   mutate(across(c(x1, x2), ~ {
        x1 <- anydate(.x)
        year(x1) <- 2020
       x1}))
      x1         x2
#1 2020-08-02 2020-11-14
#2 2020-09-04 2020-02-04
#3 2020-12-05 2020-12-10

data数据

data <- structure(list(x1 = c("2 August 2020", "4 September", "5 December 2020"
), x2 = c("11/14/2020", "2/4/2020", "12/10")), 
class = "data.frame", row.names = c(NA, 
-3L))

In base R, you could use the vectorized sub function:在基础 R 中,您可以使用矢量sub function:

a <- sub("^(((?!2020).)*)$", "\\1/2020", as.matrix(data), perl=TRUE)
data[] <- sub("([a-z])/", "\\1 ", a)
 data
                x1         x2
1    2 August 2020 11/14/2020
2 4 September 2020   2/4/2020
3  5 December 2020 12/10/2020

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM