Home > Software engineering >  change data in dataframe if variable is the same
change data in dataframe if variable is the same

Time:09-15

lets say i have the following dataframes:

df <- data.frame(name = c("jan", "piet", "mike", "hark", "don", "bon", "gin", "als"),
                 mark = c("a", "b", "c", "d", "e", "k", "n", "s"))

df2 <- data.frame(name =c("piet", "mike", "hark", "don", "jan", "gin", "als", "bon"),
                  remote = c("a1b", "a5f", "a8h", "a9k", "a4k", "als", "a4t", "a3g"))

what gives

  name mark
1  jan    a
2 piet    b
3 mike    c
4 hark    d
5  don    e
6  bon    k
7  gin    n
8  als    s

  name mark
1 piet  a1b
2 mike  a5f
3 hark  a8h
4  don  a9k
5  jan  a4k
6  gin  als
7  als  a4t
8  bon  a3g

what I want to do is, if the name df matches the name in df2, change the value of mark to the value of remote. I thought this would do the job but it did not.

df$mark[df$name == df2$name] <- df2$remote 

CodePudding user response:

Does this work:

df$mark <- df2$remote[match(df$name, df2$name)]
df
  name mark
1  jan  a4k
2 piet  a1b
3 mike  a5f
4 hark  a8h
5  don  a9k
6  bon  a3g
7  gin  als
8  als  a4t

CodePudding user response:

You can use dplyr::rows_update (given the dataframe columns have the same names)

library(dplyr)
rows_update(df, df2)

Matching, by = "name"
  name mark
1  jan  a4k
2 piet  a1b
3 mike  a5f
4 hark  a8h
5  don  a9k
6  bon  a3g
7  gin  als
8  als  a4t
  •  Tags:  
  • r
  • Related