Reputation: 109
I want to add just some specific values from column z
in dataframe df2
into dataframe df1
, but just for the id = 1 and id = 3.
I have already tried solutions with ifelse
, but for the missing values that kind of solutions work for the first value, until find the first missing gap.
df1$z <- ifelse((df1$id == df2$id), df2$z, 0)
Examples of the data:
df1 <- read.table(text = "
id v w
1 20 B
3 30 T
", h = T)
df2 <- read.table(text = "
id z b c d e f g h i j
1 100 z w e r y w u y q
2 800 t q j n m q i x z
3 700 f e q b a i e p w
4 300 a b c d a g s y q"
, h = T)
Expected result:
df1_add <- read.table(text = "
id v w z
1 20 B 100
3 30 T 700
", h = T)
Upvotes: 0
Views: 81
Reputation: 1438
Let's use left_join()
and select()
from the dplyr
package:
library(dplyr)
df1_add <- df1 %>%
left_join(df2 %>% select(id, z))
df1_add
id v w z
1 1 20 B 100
2 3 30 T 700
Upvotes: 2
Reputation: 11981
you can try this
df_add <- df1
df_add$z = df2[df2$id %in% c(1, 3), ]$z
Upvotes: 1