如何將特定值添加到特定列的行中的特定位置?我有這個名為 ID 的列:
ID
subject01_1
subject01_2
subject01_3
...
我需要在所有科目的下劃線后添加一個零:
ID
subject01_01
subject01_02
subject01_03
subject01_04
...
uj5u.com熱心網友回復:
您可以使用以下代碼在with0之后添加一個:_gsub
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
uj5u.com熱心網友回復:
使用sprintf
library(dplyr)
library(stringr)
df1 %>%
mutate(ID = str_replace(ID, "\\d $",
function(x) sprintf("d", 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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/510293.html
標籤:r细绳格式排
