giegie
giegie

Reputation: 463

Use content of the column to create a new column in R

I have a data frame like that:

V1
W_2
W_4
W_5
W_10

Numbers which come after the "_" I would like to insert in a new column

Result

V1 V2
W_2 2
W_4 4
W_5 5
W_10 10

Upvotes: 0

Views: 22

Answers (2)

akrun
akrun

Reputation: 886938

We can use

library(dplyr)
library(stringr)
df %>%
    mutate(V2 = str_remove(V1, ".*_"))

data

df <- structure(list(V1 = c("W_2", "W_4", "W_5", "W_10")), 
  class = "data.frame", row.names = c(NA, -4L))

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388797

We can use sub to remove everything before and including underscore (_)

transform(df, V2 = sub('.*_', '', V1))
#Also
#transform(df, V2 = sub('.*_(.*)', '\\1', V1))

#    V1 V2
#1  W_2  2
#2  W_4  4
#3  W_5  5
#4 W_10 10

If we want to extract a number always as shown in the example, we can use parse_number

library(dplyr)
df %>% mutate(V2 = readr::parse_number(V1))

data

df <- structure(list(V1 = c("W_2", "W_4", "W_5", "W_10")), 
      class = "data.frame", row.names = c(NA, -4L))

Upvotes: 2

Related Questions