R: set the value for certain data satisfying two conditions

I do not know how to install this simplest way. I have a dataframe called Test, with a column containing some NA values. Now I want to set the value to 1 for all fields that satisfy the following conditions:

  • line number> 60
  • if there is NA in a particular field,

So far I:

Test$MyColumn[is.na(Test$MyColumn)] <- 1

This works, but I don’t know how to set the second condition: - /

+3
source share
3 answers

If both conditions must apply before you change the item to 1in bb, here is an alternative:

aa <- 1:10
bb <- c(1,NA,6,4,NA,9,1,NA,2,5)
cc <- c(100,102,104,NA,78,54,99,NA,22,0)
dd <- data.frame(aa,bb,cc)
dd
dd$bb[4:nrow(dd)][is.na(dd$bb[4:nrow(dd)])] <- 1
dd

Here is the source dataset:

   aa bb  cc
1   1  1 100
2   2 NA 102
3   3  6 104
4   4  4  NA
5   5 NA  78
6   6  9  54
7   7  1  99
8   8 NA  NA
9   9  2  22
10 10  5   0

Here is a modified dataset:

   aa bb  cc
1   1  1 100
2   2 NA 102
3   3  6 104
4   4  4  NA
5   5  1  78
6   6  9  54
7   7  1  99
8   8  1  NA
9   9  2  22
10 10  5   0

NA 4-10 , 4-10 bb NA:

aa <- 1:10
bb <- c(1,NA,6,4,NA,9,1,NA,2,5)
cc <- c(100,102,104,NA,78,54,99,NA,22,0)
dd <- data.frame(aa,bb,cc)
dd
dd[4:nrow(dd),1:3][is.na(dd$bb[4:nrow(dd)]),] <- 1
dd

   aa bb  cc
1   1  1 100
2   2 NA 102
3   3  6 104
4   4  4  NA
5   1  1   1
6   6  9  54
7   7  1  99
8   1  1   1
9   9  2  22
10 10  5   0

NA 4-10 , 4-10 bb NA, NA bb:

aa <- 1:10
bb <- c(1,NA,6,4,NA,9,1,NA,2,5)
cc <- c(100,102,104,NA,78,54,99,NA,22,0)
dd <- data.frame(aa,bb,cc)
dd
dd[4:nrow(dd),1:3][is.na(dd$bb[4:nrow(dd)]),] <- 1
dd$bb[is.na(dd$bb)] <- 1
dd

   aa bb  cc
1   1  1 100
2   2  1 102
3   3  6 104
4   4  4  NA
5   1  1   1
6   6  9  54
7   7  1  99
8   1  1   1
9   9  2  22
10 10  5   0
+4

rownumber :

Test$RowNumber <- 1:nrow(Test)

:

Test$MyColumn[is.na(Test$MyColumn) & Test$RowNumber>60] <- 1
+3

You can get the desired result as

Test[60:nrow(Test),][is.na(Test[60:nrow(Test),])]<-1
+1
source

All Articles