Syed Ahmed
Syed Ahmed

Reputation: 209

String Concatenation in R

I am a beginner in R and I'm facing an issue with string concatenation. I've gone over a few examples over here at this site but I can't seem to understand them. Basically I have column (type - character) in a dataframe and I need to convert it to another version of it in the same dataframe.

The column that I have, and the column that I need:

  What_it_is  What_I_need
1  360055151 360.055.15.1
2  980012141 980.012.14.1
3  612650005 612.650.00.5
4  652315001 652.315.00.1
5  115670JX2 115.670.JX.2
6  360783001 360.783.00.1
7  605255005 605.255.00.5

The orientation remains the same throughout. First 3 characters then a "." then the next 3 character then a "." then the next 2 characters then a "." and then the last character.

Any help would be appreciated.

Upvotes: 0

Views: 1148

Answers (3)

latlio
latlio

Reputation: 1587

EDIT:

Thanks to r2evans for pointing out that substring is not vectorized properly (it only "sees" the first element of a vector).

Here is a revised tidyverse solution that's vectorized. Note that str_sub comes from stringrpackage.

new_df <- df %>%
  mutate(
    a1 = str_sub(a, start = 1, end = 3),
    a2 = str_sub(a, start = 4, end = 6),
    a3 = str_sub(a, start = 7, end = 8),
    a4 = str_sub(a, start = 9, end = 9)
  ) %>%
  unite("new_a", a1:a4, sep = ".")

Upvotes: 0

GordonShumway
GordonShumway

Reputation: 2056

using regular expressions you could use:

gsub("(.{3})(.{3})(.{2})(.)", "\\1\\.\\2.\\3\\.\\4",your_string)

Upvotes: 1

James
James

Reputation: 58

Try using the following code where a is your string. Is the first column actually seen as a string or a number?

paste(substr(a,1,3), substr(a,4,6), substr(a,7,8), substr(a,9,9), sep=".")

Upvotes: 3

Related Questions