aVral
aVral

Reputation: 133

Use case_when to add a new column in R

I have two DataFrame a, b that share a common column wih same variables. I wand to add the column fa from the b to the dataframe a using the case_when statement. Sofar what I achieved:

'''

a = data.frame(name = c("a","c","d"))
b = data.frame(device = c("a","c","d"), fa = c(1:3))

for ( i in 1:length(b$device)){
    a1 <- a  %>% 
    mutate( fa = case_when(
            name == b$device[i] ~b$fa[i]
                          )
          )
}

Output

name    fa
<chr>   <int>
a   NA
c   NA
d   3

I know where the problem lies, but I was not able to fix it. I would really appreciate any advice:

Expected output:

name    fa
<chr>   <int>
a   1
c   2
d   3

Upvotes: 0

Views: 705

Answers (1)

hannes101
hannes101

Reputation: 2528

I am not sure if I understand correctly, but I think, what you actually want is a left_join.

left_join(x = a
          , y = b
          , by = c("name" = "device"))

There is no need for a for loop, because dplyr works row-wise per default.

a %>%  mutate(fa = ifelse((b$device)==name,b$fa,NA)) 

Upvotes: 1

Related Questions