【问题标题】:Need to add 0 to specific location of all elements that have a specific character length需要将 0 添加到具有特定字符长度的所有元素的特定位置
【发布时间】:2020-06-15 08:12:12
【问题描述】:

很多关于如何添加前导 0 的答案,但是我的情况是这样的:

我有一个数据框,其中第一列是患者 ID,对于任何只有 3 个字符的数据框,我需要将 0 添加到 ID 的第二个字符:

patientIDs <- c("E015", "E04", "E212") #what I have
patientIDsnew <- c("E015", "E004", "E212") #what I need
hr <- c(110, 105, 135)
df <- data.frame(patientIDs,patientIDsnew, hr)

我想我需要设置一个 ifelse 来计算 str_length,如果

library(stringr)
df$patientIDsnew <- ifelse(str_length(df$patientIDs) < 4, 

【问题讨论】:

    标签: r string dataframe gsub stringr


    【解决方案1】:

    我们可以尝试使用sub 作为基本 R 选项:

    patientIDs <- c("E015", "E04", "E212")
    patientIDsnew <- sub("^([A-Z])(\\d{2})$", "\\10\\2", patientIDs, perl=TRUE)
    patientIDsnew
    
    [1] "E015" "E004" "E212"
    

    这里的想法是在单独的捕获组中匹配和捕获前导字母以及尾随两位数字(3 位 ID 将不匹配)。然后,我们可以通过添加一个填充零来替换。

    【讨论】:

    • 你是如何在正则表达式或其他方面变得如此出色的?我发现的资源非常简约
    • @Ciney 是的,大多数正则表达式文档都非常基础。我想你需要练习它才能精通它。
    【解决方案2】:

    这是一个效率较低的版本,因为我不擅长正则表达式。在“E”处拆分 ID。然后,如果任何数字 ID 的长度小于 3,则添加零。然后将它们重新组合在一起。

    patientIDs %>%
      str_split_fixed("", n = 2) %>%
      as_tibble() %>%
      mutate(V2 = if_else(str_length(V2) < 3, str_pad(V2, side = "left", width = 3, pad = "0"), V2)) %>%
      mutate(new = str_c(V1, V2))
    
    

    【讨论】:

      【解决方案3】:

      我们可以得到少于 4 个字符的patientIDs,根据它们的位置断开字符串并将它们粘贴在一起。

      patientIDsnew <- patientIDs
      inds <- nchar(patientIDsnew) < 4
      patientIDsnew[inds] <- paste0(substr(patientIDsnew[inds], 1, 1), 0, 
                                    substr(patientIDsnew[inds], 2,4))
      patientIDsnew
      #[1] "E015" "E004" "E212"
      

      【讨论】:

        猜你喜欢
        • 2015-11-08
        • 1970-01-01
        • 1970-01-01
        • 2015-06-10
        • 2022-08-23
        • 2023-03-16
        • 2015-11-18
        • 2019-03-06
        • 1970-01-01
        相关资源
        最近更新 更多