Garf
Garf

Reputation: 75

How to extract part of character data to new column

I got this df

AGE_TXT
3 weeks
1 year
3 years

i use

strsplit(df$AGE_TXT, " ")

To split data, but i have a problem how to make new column with data

I tryied to use grep("year", df$AGE_TXT), but it only give me True/False

I wolud like to make new column with data

0
1
3

0 for 3 weeks, and 1 for 1 year, 3 for 3 years

Upvotes: 0

Views: 443

Answers (1)

Sotos
Sotos

Reputation: 51592

You can use ifelse

df$new <- ifelse(grepl('year', df$AGE_TXT), gsub('\\D', '', df$AGE_TXT), 0)
df
#  AGE_TXT new
#1 3 weeks  0
#2  1 year  1
#3 3 years  3

Upvotes: 1

Related Questions