csarvf_01
csarvf_01

Reputation: 61

Creating a new column in R, based on other columns with additional condition

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

Answers (4)

TarJae
TarJae

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

717
717

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

akrun
akrun

Reputation: 887108

Using mutate

library(dplyr)
df %>%
    mutate(C = 1000 * A + B)

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101335

You can try the code below

transform(df, C = 1000*A + B)

Upvotes: 1

Related Questions