Reputation: 61
I want to create a new column in my data frame based on the other two columns, but the new column also has to be a 4-digit code.
A B
1 2
1 3
..
1 10
these are my two columns that I have. I want a third column C to be those first ones combined, but to a 4-digit code. Kind of like this.
A B C
1 2 1002
1 3 1003
...
1 10 1010
I hope I made it clear. Is there a way to do it?
Upvotes: 2
Views: 77
Reputation: 78927
There is no doubt that akrun's and ThomasIsCoding solutiona are best. Here a wrapper of 717 solution!
library(dplyr)
library(stringr)
df %>%
mutate(across(c(A, B), ~str_pad(., 2, pad = "0")),
c = str_c(A, B))
A B c
<chr> <chr> <chr>
1 01 02 0102
2 01 03 0103
3 01 10 0110
Upvotes: 1
Reputation: 36
how many digits for column A
Suppose there may be 2 digits in column A
library(dplyr)
df <- data.frame(
A = c(1:20),
B = c(20:1)
)
df %>%
mutate(
C1 = stringr::str_pad(A, 2, pad = "0"),
C2 = stringr::str_pad(B, 2, pad = "0"),
) %>%
tidyr::unite("C", C1:C2, sep = "")
Upvotes: 1