I have data from another program with poor formatting where each company's name is given once as a header, but then NA
for each subsequent record.
company invoice item
<chr> <dbl> <dbl>
A NA NA
NA 1 5
NA 1 3
B NA NA
NA 2 2
C NA NA
NA 3 4
NA 4 7
NA 4 6
NA 5 8
I want to iterate through company
replacing the NA
values for each company with their name:
company invoice item
<chr> <dbl> <dbl>
A NA NA
A 1 5
A 1 3
B NA NA
B 2 2
C NA NA
C 3 4
C 4 7
C 4 6
C 5 8
Because the first instance of each company's name is correct, it made sense to me to use the index of company[[i - 1]]
for each instance of NA
. So, I was trying to iterate through the indexes with variations on the following:
df$company <- for (i in seq_along(df$company)) {
if (is.na(df$company[[i]]) == TRUE) {
df$company[[i]] = df$company[[i - 1]]
} else {
df$company[[i]] = df$company[[i]]
}
}
Either it returns the df
with company
missing, or it returns NULL
. What do I need to change to get the result I want?