Dreamer_y19th
Dreamer_y19th

Reputation: 25

how can I create new ID column using R

I am working on csv file and trying to assign new id of rows with No ID of the whole csv file.

what I have          I would like to create NewID Number
Id number   ------->      NewId number
1245                        1245
1367                        1367
NoID                        NoID_1
1468                        1468
NoID                        NoID_2
NoID                        NoID_3
1456                        1456

Upvotes: 2

Views: 99

Answers (1)

akrun
akrun

Reputation: 886938

An option is to convert to numeric to find the ones that are not numeric

i1 <- is.na(as.numeric(df1[["ID number"]]))
df1$NewId <- df1[["ID number"]]
df1$NewId[i1] <- paste0(df1[["ID number"]][i1], "_", seq(sum(i1)))

Or if we don't want to get warning message by the conversion to numeric, use a regex pattern

i1 <- !grepl("^\\d+$", df1[["ID number"]]) 

data

df1 <-structure(list(`ID number` = c("1245", "1367", "NoID", "1468", 
"NoID", "NoID", "1456")), class = "data.frame", row.names = c(NA, 
-7L))

Upvotes: 2

Related Questions