I don't know how to set this the easiest way. I have a dataframe called Test, with a column containing some NA values. Now I want to set a value of 1 to all fields meeting the following conditions:
So far I have:
Test$MyColumn[is.na(Test$MyColumn)] <- 1
This works, but I don't know how to set the second condition :-/
If both conditions must apply before you change an element to 1 in 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 original data set:
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 the modified data set:
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
This changes NA in rows 4-10 of all columns if there is an NA in rows 4-10 of 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
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
This changes NA in rows 4-10 of all columns if there is an NA in rows 4-10 of bb then it changes all remaining NA in 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With