Reputation: 663
I have two vectors:
vec1 <- c("222", "AA-AA", "GGH-GGH", "GGGD")
vec2 <- c("222", "AA-AA", "GGG-GGH", "GGGD")
I would like to paste them at defined positions only
postions <- c(TRUE, FALSE, FALSE, TRUE)
The result I want is
222-222, AA-AA, GGH-GGH, GGGD-GGGD)
How do I get this in R?
I tried paste(vec1[positions], vec2[positions], sep = "-")
but did not get as expected.
This is the actual data:
vec1 <- c("226883824", "226883824", "226883824", "232844096", "232844096",
"232844096", "232844096", "232847517-232847519", "232847517-232847519",
"232847517-232847519", "232847517-232847519", "232847538", "232847538",
"232847538", "232847538")
vec2 <- c("226883824", "226883824", "226883824", "232844096", "232844096",
"232844096", "232844096", "232847517-232847519", "232847517-232847519",
"232847517-232847519", "232847517-232847519", "232847538", "232847538",
"232847538", "232847538")
positions <- c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE,
FALSE, TRUE, TRUE, TRUE, TRUE)
So, in my solution, I do not want anything appended to "232847517-232847519", "232847517-232847519", "232847517-232847519"
as they already have what I intend to do.
Upvotes: 1
Views: 36
Reputation: 887118
Perhaps, we can use indexing on the logical vector to subset both the vector
s, paste
and assign the output back to one of the vector
vec1[postions] <- paste(vec1[postions], vec2[postions], sep="-")
vec1
#[1] "222-222" "AA-AA" "GGH-GGH" "GGGD-GGGD"
With OP's new data
vec1[positions] <- paste(vec1[positions], vec2[positions], sep="-")
vec1
#[1] "226883824-226883824" "226883824-226883824" "226883824-226883824" "232844096-232844096" "232844096-232844096" "232844096-232844096"
#[7] "232844096-232844096" "232847517-232847519" "232847517-232847519" "232847517-232847519" "232847517-232847519" "232847538-232847538"
#[13] "232847538-232847538" "232847538-232847538" "232847538-232847538"
Or with ifelse/strrep
(using the OP's updated dataset)
trimws(ifelse(grepl("-", vec1), vec1,
strrep(paste0(vec1, "-"), 2)), whitespace = "-")
#[1] "226883824-226883824" "226883824-226883824" "226883824-226883824" "232844096-232844096" "232844096-232844096" "232844096-232844096"
#[7] "232844096-232844096" "232847517-232847519" "232847517-232847519" "232847517-232847519" "232847517-232847519" "232847538-232847538"
#[13] "232847538-232847538" "232847538-232847538" "232847538-232847538"
Upvotes: 1