normally when I want to update a variable in R I perform the normal assignment:
df[var] <- new_vector
But let's say new_vector
has many NAs and non-NAs values. I would like to only change values of df[var]
for which new_vector
is not NA and leave them unchanged for those rows if new_vector is NA
new_vector <- c(0, NA, NA, 0, 1)
df <- data.frame(1:5,11:15)
colnames(df) <- c("A", "B")
df
# A B
#1 1 11
#2 2 12
#3 3 13
#4 4 14
#5 5 15
df["B"] <- new_vector
df
#got:
# A B
#1 1 0
#2 2 NA
#3 3 NA
#4 4 0
#5 5 1
#
#but I intend:
# A B
#1 1 0
#2 2 12
#3 3 13
#4 4 0
#5 5 1