I'm looking for a way to fillNA in duplicated()
rows. There are totally same rows and at one time there is a NA, so I decide to fill this one by value of complete row but I don't see how to deal with it.
Using the duplicated()
function, I could have a data frame like that:
df <- data.frame(
Year = rnorm(5),
hour = rnorm(5),
LOT = rnorm(5),
S123_AA = c('ABF4576','ABF4576','ABF4576','ABF4576','ABF4576'),
S135_AA = c('ABF5403',NA,'ABF5403','ABF5403','ABF5403'),
S13_BB = c('BF50343','BF50343','BF50343','BF50343',NA),
S1763_BB = c('AA3489','AA3489','AA3489','AA3489','AA3489'),
S173_BB = c('BQA0478','BQA0478','BQA0478','BQA0478','BQA0478'),
S234543 = c('AD4352','AD4352','AD4352','AD4352','AD4352'),
S1265UU5 = c('AZERTY', 'AZERTY', 'AZERTY', 'AZERTY','AZERTY')
)
The rows are similar, so how could I feel the NA by the value of the preceding raw (which is not an NA) ? There is no complete.cases()
rows.
You could loop through the data and find the first none NA value and replace the NA values with that value
Or alternatively you could review your data element by element and take a none NA value from either above or below the relevant cell using nested for loops.
You can do the following:
reading your question made me think of an imputation problem for the dataframe.
In other terms you need to fill the NAs with some sort of value to be able to "save" records in the dataframe. The simplest way is to select the value of a particular column by searching the mean (when dealing with cardinal values) or the mode (when dealing with categorical values) [you may also execute a regression, but I guess it's a more complex method].
In this case we may choose the mode replacement because the attributes are categorical. By running your code we obtain the dataframe
df
:We can then create a function to calculate the mode of a particular column:
And then use it to fill the missing values. Below the code to impute the missing values for the column
S135_AA
(I created a new dataframe namedworkdf
) :This is the output where you can see that the column
S135_AA
NAs took the most recurring value of the colum:If your objective was data cleaning I guess that you should use an imputation method to deal with it.