BioMan
BioMan

Reputation: 704

add number to strings in data frame

How do I assign numbers to a string in a data frame like below?

I tried something like this, but its not correct: row.names(d) <- paste(d[,1],1:96,sep="")

> head(d,10)
   condition
1          T
2          N
3          T
4          N
5          T
6          N
7          T
8          N
9          T
10         N

output:

   condition
T1          T
N1          N
T2          T
N2          N
T3          T
N3          N
T4          T
N4          N
T5          T
N5          N

Upvotes: 2

Views: 502

Answers (1)

David Arenburg
David Arenburg

Reputation: 92292

Using row names is generally a bad practice because they become meaningless the moment you start manipulating the data. Nevertheless, you could achieve your desired output using

row.names(d) <- with(d, ave(as.character(condition), condition, FUN = function(x) paste0(x, seq(length(x)))))
d
#    condition
# T1         T
# N1         N
# T2         T
# N2         N
# T3         T
# N3         N
# T4         T
# N4         N
# T5         T
# N5         N  

Though I'd recommend something like

d$res <- with(d, ave(as.character(condition), condition, FUN = function(x) paste0(x, seq(length(x)))))

Some other alternatives could be

library(data.table) 
setDT(d)[, res := paste0(condition, seq_len(.N)), by = condition]

Or (don't run this on a data.table object)

library(dplyr)  
library(magrittr)
d %<>% 
  group_by(condition) %>% 
  mutate(res = paste0(condition, row_number()))

There could be some options which I'll leave to other people to figure out.

Upvotes: 3

Related Questions