What I have: I have two data frames. They both have the same column and row names and the same dimensions (equal number of rows and columns):
records <- read.table(text =" D0 D1 D2 D3
1 0 0 1 NA
2 1 1 1 1
3 1 0 NA 1
4 0 NA 0 0", header = TRUE)
covariate <- read.table(text =" D0 D1 D2 D3
1 70 1 6 3
2 121 4 8 5
3 86 3 2 4
4 141 2 5 2", header = TRUE)
What I want: To replace specific values in the 'covariate' data frame with NAs. The values to replace are those who are in the exact same place that correspond to where 'records' have NAs. The result should look like this:
covariate_fixed <- read.table(text =" D0 D1 D2 D3
1 70 1 6 NA
2 121 4 8 5
3 86 3 NA 4
4 141 NA 5 2", header = TRUE)
The closest threads I could find to my problem were these: Replace values from another dataframe by IDs and Replace values from another dataframe by IDs However, I don't have matching values in both files except for the column and row names, and the rule to replace is given not by specific ID but for a specific location in the data frame. I found other posts of similar nature as well but none I could find a way to adapt to my specific problem.
Could someone help me produce a code in R to do this? Thanks!
is.na(covariate) <- is.na(records)
gives
> covariate
D0 D1 D2 D3
1 70 1 6 NA
2 121 4 8 5
3 86 3 NA 4
4 141 NA 5 2
Tips:
is.na<-
is useful for making things missingi,j
or just i
, so when of same dimensions, you don't have to think too hard about copying attributes of one data frame over to another.