[英]Filter to remove all rows before a particular value in a specific column, while this particular value occurs several time
[英]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.