0

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)
2
  • 2
    What about merge merge(df1, df2[c("id", "z")]) Commented Apr 17, 2019 at 12:41
  • 1
    @akrun It works pretty good thank you! Commented Apr 17, 2019 at 13:02

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @tomasu, I really want to use dplyr package but I didn't know how to use it.
1

you can try this

df_add <- df1
df_add$z = df2[df2$id %in% c(1, 3), ]$z

Comments

1

We can use merge from base R

merge(df1, df2[c("id", "z")])

Comments

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.