Jeni
Jeni

Reputation: 958

Use different separators in the same paste statement R

I am trying to join three columns of a dataframe in one:

Chr    Start    End
1       100      105
2       400      420

I would like to obtain the coordinates in a column and I am trying this:

apply(df, 1, function(x) paste0(i[,1], i[,2], i[,3], sep=c(':', '-')))

This is working except for the separators, because I am not obtaining the "-" as the second separator, so my output is this:

coord
1:100:105
2:400:420

While my desired output would be :

coord
1:100-105
2:400-420

How can I use a second separator in the same paste statement?

Upvotes: 1

Views: 902

Answers (3)

akrun
akrun

Reputation: 887183

An option with str_c

library(stringr)
library(dplyr)
df %>%
  mutate(coord = str_c(Chr, ":", Start, "-", End))

Upvotes: 1

Ben
Ben

Reputation: 30474

A couple of other alternatives to consider using dplyr and paste0 or sprintf:

library(tidyverse)

df %>%
  mutate(coord = paste0(Chr, ":", Start, "-", End))

df %>%
  mutate(coord = sprintf("%d:%d-%d", Chr, Start, End))

Output

  Chr Start End     coord
1   1   100 105 1:100-105
2   2   400 420 2:400-420

Upvotes: 2

Sathish
Sathish

Reputation: 12713

You can't use two separator characters in a paste() statement. Please read the help page of ?paste. It says:

sep = a character string to separate the terms. Not NA_character_.

df$coord <- apply(df, 1, function(x) paste(paste(x[1], x[2] , sep=':'), x[3], sep='-'))
df
#   Chr Start End     coord
# 1   1   100 105 1:100-105
# 2   2   400 420 2:400-420

Upvotes: 3

Related Questions