student_R123
student_R123

Reputation: 1002

Making the rows of a data frame to NAs using R

I have a data frame as follows,

aid=c(1:10)
x1_var=rnorm(10,0,1)
x2_var=rnorm(10,0,1)
x3_var=rbinom(10,1,0.5)

data=data.frame(aid,x1_var,x2_var,x3_var)


 head(data)
  aid      x1_var     x2_var x3_var
1   1 -0.99759448 -0.2882535      1
2   2 -0.12755695 -1.3706875      0
3   3  1.04709366  0.8977596      1
4   4  0.48883458 -0.1965846      1
5   5 -0.40264114  0.2925659      1
6   6 -0.08409966 -1.3489460      1

I want to make the all the rows in this data frame completely to NA if x3_var==1(without making aid column to NA)

I tried the following code.

 > data[which(data$x3_var==1),]=NA
> data
   aid      x1_var     x2_var x3_var
1   NA          NA         NA     NA
2    2 -0.12755695 -1.3706875      0
3   NA          NA         NA     NA
4   NA          NA         NA     NA
5   NA          NA         NA     NA
6   NA          NA         NA     NA
7   NA          NA         NA     NA
8    8 -1.78160459 -1.8677633      0
9    9 -1.65895704 -0.8086148      0
10  10 -0.06281384  1.8888726      0

But this code have made the values of aid column also to NA. Can anybody help me to fix this?

Also are there any methods that do the same thing?

Thank you

Upvotes: 1

Views: 27

Answers (2)

neilfws
neilfws

Reputation: 33772

A dplyr solution. Assuming the columns to be altered begin with "x" as in the example data.

library(dplyr)

set.seed(1001)
df1 <- data.frame(aid = 1:10,
                  x1_var = rnorm(10,0,1),
                  x2_var = rnorm(10,0,1),
                  x3_var = rbinom(10,1,0.5))

df1 %>% 
  mutate(across(starts_with("x"), ~ifelse(x3_var == 1, NA, .x)))

   aid     x1_var     x2_var x3_var
1    1  2.1886481  0.3026445      0
2    2 -0.1775473  1.6343924      0
3    3         NA         NA     NA
4    4 -2.5065362  0.4671611      0
5    5         NA         NA     NA
6    6 -0.1435595  0.1102652      0
7    7         NA         NA     NA
8    8 -0.6229437 -1.0302508      0
9    9         NA         NA     NA
10  10         NA         NA     NA

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388817

Your code would work if you remove aid column from it.

data[which(data$x3_var==1),-1]=NA

You can also do this without which :

data[data$x3_var==1, -1]=NA

In the above two cases I am assuming that you know the position of aid column i.e 1. If in reality you don't know the position of the column you can use match to get it's position.

data[data$x3_var==1, -match('aid', names(data))] = NA

Upvotes: 2

Related Questions