Ask Your Question
2

How can the missing values in vector A be substituted with particular values from vector B while simultaneously changing the values in vector B to NAs?

asked 2023-02-16 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-11-09 00:00:00 +0000

david gravatar image

You can use the is.na() function to identify the missing values in vector A and then use the logical index to replace the missing values with the corresponding values from vector B. At the same time, you can set those values in vector B to NA using the same logical index. Here is an example:

# Example vectors
A <- c(1, 2, NA, 4, NA, 6)
B <- c(10, 20, 30, 40, 50, 60)

# Identify missing values in A
missing_A <- is.na(A)

# Replace missing values in A with values from B and set corresponding values in B to NA
B[missing_A] <- NA
A[missing_A] <- B[missing_A]

# Print result
A
# [1]  1  2 30  4 50  6
B
# [1] 10 20 NA 40 NA 60

In this example, the missing values in vector A are replaced with the corresponding values from vector B (30 and 50), while those values in vector B are set to NA.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-02-16 11:00:00 +0000

Seen: 10 times

Last updated: Nov 09 '21