Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing NAs in a column with the values of other column

I wonder how to replace NAs in a column with the values of other column in R using dplyr. MWE is below.

Letters <- LETTERS[1:5]
Char    <- c("a", "b", NA, "d", NA)
df1 <- data.frame(Letters, Char)
df1

library(dplyr]

df1 %>%
  mutate(Char1 = ifelse(Char != NA, Char, Letters))

     Letters Char Char1
1       A    a    NA
2       B    b    NA
3       C <NA>    NA
4       D    d    NA
5       E <NA>    NA
like image 934
MYaseen208 Avatar asked Sep 10 '17 03:09

MYaseen208


People also ask

How do you replace Na in a column in a Dataframe?

You can replace NA values with blank space on columns of R dataframe (data. frame) by using is.na() , replace() methods. And use dplyr::mutate_if() to replace only on character columns when you have mixed numeric and character columns, use dplyr::mutate_at() to replace on multiple selected columns by index and name.

How do I replace NAs with values in R?

Replace NA with 0 in R Data Frame To replace NA with 0 in an R data frame, use is.na() function and then select all those values with NA and assign them to 0. myDataframe is the data frame in which you would like replace all NAs with 0.

How do I replace a value in a specific column in R?

replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values. It takes on three parameters first is the list name, then the index at which the element needs to be replaced, and the third parameter is the replacement values.


1 Answers

You can use coalesce:

library(dplyr)

df1 <- data.frame(Letters, Char, stringsAsFactors = F)

df1 %>%
  mutate(Char1 = coalesce(Char, Letters))

  Letters Char Char1
1       A    a     a
2       B    b     b
3       C <NA>     C
4       D    d     d
5       E <NA>     E
like image 140
Z.Lin Avatar answered Oct 10 '22 20:10

Z.Lin