Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append value in df rows

I have a column in dataframe (df) for which I want to append value (not constant, instead variable). An example will make it more clear:

> df
     geneID Sample.290
1         1  0.4018499
2        10  0.2694255
3       100  1.4441846
4      1000 13.7652753
5     10000  2.1552100
6 100008586  0.2358481

I want to append character "ENSG" and multiple "000" so that total length of the each value will be 15 (including ENSG). For example the output should be:

         geneID           Sample.290
1        ENSG00000000001  0.4018499
2        ENSG00000000010  0.2694255
3        ENSG00000000100  1.4441846
4        ENSG00000001000 13.7652753
5        ENSG00000010000  2.1552100
6        ENSG00100008586  0.2358481
like image 786
Newbie Avatar asked Aug 11 '26 20:08

Newbie


2 Answers

Using str_pad from stringr,

library(stringr)
df$geneID <- paste0('ENSG', str_pad(df$geneID, width = 11, pad = '0'))
df
#           geneID Sample.290
#1 ENSG00000000001  0.4018499
#2 ENSG00000000010  0.2694255
#3 ENSG00000000100  1.4441846
#4 ENSG00000001000 13.7652753
#5 ENSG00000010000  2.1552100
#6 ENSG00100008586  0.2358481
like image 162
Sotos Avatar answered Aug 14 '26 09:08

Sotos


Using basic function:

df$geneID <- sapply(df$geneID,function(x) paste("ENSG",
                    paste(rep(0,(15-nchar(x)-nchar("ENSG"))),collapse = ""),x,sep=""))

"15" total length of variable;

like image 31
SatishR Avatar answered Aug 14 '26 09:08

SatishR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!