-3

In a column of 7000 rows there are 11 NA's. I want to replace those NA's with the product of two other columns in my data frame

The column with NA's is TOTALCHARGES and the two columns I want to multiply are TENURE and MONTHLYCHARGES.

tyluRp
  • 4,678
  • 2
  • 17
  • 36

2 Answers2

1

Find the indices of the missing data:

na.vals <- which(is.na(your_data$TOTALCHARGES))

Modify the relevant elements of TOTALCHARGES (within the data set):

your_data <- transform(your_data,
       TOTALCHARGES=replace(TOTALCHARGES,na.vals,
           TENURE[na.vals]*MONTHLYCHARGES[na.vals]))
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
1

Something like this (assuming df is your data.frame)?

df[is.na(df$TOTALCHARGES), "TOTALCHARGES"] <- df[is.na(df$TOTALCHARGES), "TENURE"] * df[is.na(df$TOTALCHARGES), "MONTHLYCHARGES"]
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68