1

I want to create a new column based on whether a string is present in a different column of the dataframe.

 name
  Jon
  Anne
Jobraith
  Knut

Becomes:

 name      dummy
  Jon        1
  Anne       0
Jobraith     1
  Knut       0

looking for something along the lines of:

df$dummy <- ifelse('jo' in df$name, 1, 0)

1 Answer 1

3

You could use grepl( ... ) to check for the substring ...

df <- data.frame(name = c('Jon', 'Anne', 'Jobraith', 'Knut'))
df$dummy <- as.numeric(grepl('jo', df$name, ignore.case=T))
df

#       name dummy
# 1      Jon     1
# 2     Anne     0
# 3 Jobraith     1
# 4     Knut     0
Sign up to request clarification or add additional context in comments.

2 Comments

Why would you use ifelse here? Why not just as.numeric?
ifelse is nice though because it's a bit more general in the case that 0,1 isn't wanted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.