Erin Winkler
Erin Winkler

Reputation: 11

Check if string is in column of dataframe and if it's not, add it to the end of the dataframe with a value 0?

I two dataframes like this:

df1:

Letter Value
A       5
C       2
E       3

And df2:

Letter 
A
B  
C
D  
E 

And I want to find cases when a Letter in df2 does not match a Letter in df1 and when that happens, add the Letter from df2 to df1 and give it the value 0.

So:

Letter Value
A      5
B      0
C      2
D      0
E      3

Any help would be great. I'm not very strong in R at all.

EDIT: I tried something like this but it's not working:

for (i in df1$Name){
  for (j in df2$Name){
    if(strcmpi(i, j)){
      # do nothing
    } else{
      rbind(df1, df2[i,])
    }  
  }
}

Upvotes: 1

Views: 30

Answers (1)

IRTFM
IRTFM

Reputation: 263332

df2 $Value <- ifelse (df2$Letter %in% df1$Letter,   # condition
                       df1$Value[match(df2$Letter,df1$Letter)], #value if TRUE
                       0)   # itherwise
df2
  Letter Value
1      A     5
2      B     0
3      C     2
4      D     0
5      E     3

The match function is designed to return indices for other vectors, and it will have a length that is as long as its first argument.

Upvotes: 1

Related Questions