MyQ
MyQ

Reputation: 469

Get rid of extra sep in the paste function in R

I am trying to get rid of the extra sep in the paste function in R. It looks easy but I cannot find a non-hacky way to fix it. Assume l1-l3 are lists

l1 = list(a=1)
l2 = list(b=2)
l3 = list(c=3)
l4 = list(l1,l2=l2,l3=l3)

note that the first element of l4 is not named. Now I want to add a constant to the names like below:

names(l4 ) = paste('Name',names(l4),sep = '.')

Here is the output:

 names(l4)
[1] "Name."   "Name.l2" "Name.l3"

How can I get rid of the . in the first output (Name.)

Upvotes: 2

Views: 338

Answers (1)

akrun
akrun

Reputation: 887193

We can ue trimws (from R 3.6.0 - can specify whitespace with custom character)

trimws(paste('Name',names(l4),sep = '.'), whitespace = "\\.")
#[1] "Name"    "Name.l2" "Name.l3"

Or with sub to match the . (. is a metacharacter for any character, so we escape \\ to get the literal meaning) at the end ($) of the string and replace with blank ("")

sub("\\.$", "", paste('Name',names(l4),sep = '.'))

If the . is already there in the names at the end, we can use an index option

ifelse(nzchar(names(l4)), paste("Name", names(l4), sep="."), "Name")
#[1] "Name"     "Name.l2." "Name.l3" 

Upvotes: 3

Related Questions