Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

What I have done is I have use more 'untidy'IDs like,

df1 <- data.frame(id=c("A-1","A-10","A-100","b-1","b-10","b-100"),n=c(1,2,3,4,5,6))

from this IDs, I want to assign new 'tidy' IDs like,

df2 <- data.frame(id=c("A0001","A0010","A0100","B0001","B0010","B0100"),n=c(1,2,3,4,5,6))

(now I need capital 'B' instead of 'b')

I tried to use str_pad functiuon, but I couldn't able to do that.

1 Answer

0 votes
by (107k points)

In R programming, we can separate the data into different columns based on "-", then you have to convert the letters to uppercase, using sprintf pad with 0's and combine the two columns with unite.

library(dplyr)

library(tidyr)

df1 %>%

  separate(id, c("id1", "id2"), sep = "-") %>%

  mutate(id1 = toupper(id1), 

         id2 = sprintf('s', id2)) %>%

  unite(id, id1, id2, sep = "")

#     id n

#1 A0001 1

#2 A0010 2

#3 A0100 3

#4 B0001 4

#5 B0010 5

#6 B0100 6 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...