簡體   English   中英

如何在特定列的行中向特定 position 添加特定值?

[英]How to add a particular value to a particular position in rows of a specific column?

如何在特定列的行中向特定 position 添加特定值? 我有這個名為 ID 的列:

ID
subject01_1
subject01_2
subject01_3
...

我需要在所有科目的下划線后添加一個零:

ID
subject01_01
subject01_02
subject01_03
subject01_04
... 

您可以使用以下代碼在帶有gsub_之后添加0

df <- read.table(text = "ID
subject01_1
subject01_2
subject01_3", header = TRUE)

df$ID <- gsub("\\_(\\d+)", "\\_0\\1", df$ID)
df
#>             ID
#> 1 subject01_01
#> 2 subject01_02
#> 3 subject01_03

使用reprex v2.0.2創建於 2022-09-25

使用sprintf

library(dplyr)
library(stringr)
df1 %>%
    mutate(ID = str_replace(ID, "\\d+$",
        function(x) sprintf("%02d", as.numeric(x))))

-輸出

   ID
1 subject01_01
2 subject01_02
3 subject01_03

數據

df1 <- structure(list(ID = c("subject01_1", "subject01_2", "subject01_3"
)), class = "data.frame", row.names = c(NA, -3L))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM