I have a data.frame
that looks like this:
df <- structure(list(
a = c("atg", "tga", "agt", "acc", "cgt", "gca",
"gtc", "ggg", "ccc"),
b = c("1", "2", NA, "3", NA, NA, "4", "5",
"6")
),
row.names = c(NA, -9L),
class = "data.frame")
I have replaced the NAs
with the nearest non-NA
using na.locf
from the zoo
package, but I need to add an incremental letter to the replaced NA
values, so that the end product looks like this:
> df
a b
1 atg 1
2 tga 2
3 agt 2a
4 acc 3
5 cgt 3a
6 gca 3b
7 gtc 4
8 ggg 5
9 ccc 6
I wrote a small if
function, that fills the NA
appropriately but adds letters to all values and recycles the numbers to match the length of letters
. I can see that this result is from the any
call within the function I am now thinking I probably need to do a for
loop and use that to increment through each cell, however a for
loop with a variant of the if
statement doesn't do anything. Any suggestions are welcome.
> testif <- function(x) {
+ if (any(is.na(x))) {
+ paste(na.locf(x), letters, sep = "")
+ }
+ }
for (x in df$b) {
+ if (any(is.na(x))) {
+ paste(test$b, na.locf(x), letters, sep = "")
+ }
+ }