user7064
user7064

Reputation: 217

R: accessing cells in a data frame

df1 and df2 are two dataframes (code below).

> df1
  X1 X2 X3 X4 X5
1  1  2  3  4  5
2  6  7  8  9 10
3 11 12 13 14 15

> df2
   row col  drop
1    1   1 FALSE
2    2   1 FALSE
3    3   1  TRUE
4    1   2 FALSE
5    2   2 FALSE
6    3   2 FALSE
7    1   3  TRUE
8    2   3 FALSE
9    3   3 FALSE
10   1   4 FALSE
11   2   4 FALSE
12   3   4 FALSE
13   1   5 FALSE
14   2   5 FALSE
15   3   5 FALSE

Using the information from df2, I would like to transform df1 into

> df1
  X1 X2 X3 X4 X5
1  1  2  NA  4  5
2  6  7  8  9 10
3 NA  12 13 14 15

How would you do this?


Code to create df1 and df2:

library(dplyr)
df1 <- data.frame(matrix(1:15, nrow = 3, ncol = 5, byrow = TRUE))
df2 <- expand.grid(row = 1:3, col = 1:5) %>%
  mutate(drop = c(rep(FALSE, 2), TRUE, rep(FALSE, 3), TRUE, rep(FALSE, 8)))

Upvotes: 2

Views: 89

Answers (2)

akrun
akrun

Reputation: 886948

As we are using dplyr, we can make use of the chain

library(dplyr)
df2 %>%
    filter(drop) %>% 
    select(-drop) %>%
    as.matrix %>% 
    replace(df1, ., NA)
#  X1 X2 X3 X4 X5
#1  1  2 NA  4  5
#2  6  7  8  9 10
#3 NA 12 13 14 15

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388817

Subset only TRUE values from df2, convert it into matrix and assign NA to those row and column indices in df1.

df1[as.matrix(df2[df2$drop, -3])] <- NA

df1
#  X1 X2 X3 X4 X5
#1  1  2 NA  4  5
#2  6  7  8  9 10
#3 NA 12 13 14 15

Upvotes: 1

Related Questions