Hello,
I'm trying to create a new variable 'value' in the data frame, and assign either the value of its corresponding 'src' or 'dst' if 'group' is either 'A' or 'B'. But I get 'NA' in 'B' instead of 'C1' ('dst') with a warning of ': invalid factor level, NA generated'
Could anyone help me to understand what the issue is with the factors here?
What am I doing wrong and what is the right way to do it?
Many thanks in advance,
library(tidyverse)
#> Warning: package 'ggplot2' was built under R version 3.6.2
dF <- data.frame(
group = c("A","A","B"),
src = c("O1","O2", "O3"),
dst = c("C1","C2","C1")
)
dF <- dF %>%
mutate(
value = group == "A",
value = if_else(value == TRUE, src, dst)
)
#> Warning in `[<-.factor`(`*tmp*`, i, value = structure(1L, .Label =
#> c("C1", : invalid factor level, NA generated
dF
#> group src dst value
#> 1 A O1 C1 O1
#> 2 A O2 C2 O2
#> 3 B O3 C1 <NA>
Created on 2021-07-14 by the reprex package (v2.0.0)