Reputation: 81
Let's imagine you have a dataframe with two columns ID
and POSITION
. I want to paste some text depending on the ID value.
I want to paste the ID value with GK0000
(when ID>10) or GK00000
(when ID<10) along with .2:
, POSITION
value, ..
and the following POSITION
value (POSITION+1)
For example if ID = 1
and POSITION = 10
, the result would be GK000001.2:10..11 and if ID = 10
and POSITION = 10
, the result would be GK000010.2:10..11
In Excel I can do this being A
as ID
and B
as POSITION
using =IF(A2<10,CONCATENATE("GK00000",A2,".2:",B2,"..",B2+1),CONCATENATE("GK0000",A2,".2:",B2,"..",B2+1))
but I want to add it to my R script line.
I give you a short example of my input data just ilustrative
ID <- c(1,5,9,10,12)
POSITION <- c(10,50,90,100,120)
df <- cbind(ID,POSITION)
and the result I'm expecting is
CONCAT <- c("GK000001.2:10..11","GK000005.2:50..51","GK000009.2:90..91",
"GK000010.2:100..101","GK000012.2:120..121")
dfResult <- cbind(ID,POSITION,CONCAT)
Upvotes: 0
Views: 404
Reputation: 76651
I believe the question asks for a string format given two arguments, A
and B
and a number of digits.
concat <- function(A, B, digits = 6){
fmt <- paste0("%0", digits, "d")
fmt <- paste0("GK", fmt, ".2:%d..%d")
sprintf(fmt, A, B, B + 1)
}
concat(df[, 'ID'], df[, 'POSITION'], 6)
# [1] "GK000001.2:10..11" "GK000002.2:20..21" "GK000003.2:30..31"
# [4] "GK000004.2:40..41" "GK000005.2:50..51" "GK000006.2:60..61"
# [7] "GK000007.2:70..71" "GK000008.2:80..81" "GK000009.2:90..91"
#[10] "GK000010.2:100..101" "GK000011.2:110..111" "GK000012.2:120..121"
Upvotes: 1