mardi 10 août 2021

if a value in one column does not exist fill in with another value in r

In the following df

df <- data.frame(
  A = c("a", "b", "c", "d"),
  B = c("0,1","0,2","0,12","0,11"))

I want to create a new column "C" which has the value from column "B" corresponding to "d" from column "A" . I first extract the value corresponding to "d" and then add it to the df.

row.names(df) <- df$A
C <- df["d", "B"] 
> df
  A    B    C
  a  0,1 0,11
  b  0,2 0,11
  c 0,12 0,11
  d 0,11 0,11

I would like a solution in case "d" doesn't exist in column "A", then I would like to get the value for "c" in column "C".


> df
  A    B    C
  a  0,1 0,12
  b  0,2 0,12
  c 0,12 0,12

I tried the case_when

row.names(df) <- df$A
df <- df %>% mutate(C = case_when(A == "d" ~ paste(df["d", "B"]), A == "c" ~ paste(df["c", "B"])))

but if the "d" doesn't exist, I get this and cannot fill in the NA with the value

> df
  A    B    C
a a  0,1 <NA>
b b  0,2 <NA>
c c 0,12 0,12

If "d" exists, I get this

> df
  A    B    C
a a  0,1 <NA>
b b  0,2 <NA>
c c 0,12 0,12
d d 0,11 0,11

Aucun commentaire:

Enregistrer un commentaire