0

I want to have a column's values equal another column's values if the first column's value is NA in this row. So I want to change something like this

A  B
3  NA
NA NA
NA NA
5  NA
NA NA
NA NA
7  5

to something like this

A  B
3  3
NA NA
NA NA
5  5
NA NA
NA NA
7  5

I am fairly new to R and any other kind of programming.

phiver
  • 23,048
  • 14
  • 44
  • 56
ArOk
  • 193
  • 7
  • 1
    suppose your data is in a `data.frame` called `dat`: `ifelse(is.na(dat$B), dat$A, dat$B)` – bouncyball Jul 15 '18 at 13:20
  • 1
    Have a look at `dplyr::coalesce()`. It will make problem simpler. – MKR Jul 15 '18 at 13:22
  • 1
    Possible duplicate of [Combine column to remove NA's](https://stackoverflow.com/questions/14563531/combine-column-to-remove-nas) – MKR Jul 15 '18 at 13:59

2 Answers2

0

try:

df$B[is.na(df$B)] <- df$A
Zahiro Mor
  • 1,708
  • 1
  • 16
  • 30
0

As per OP's description:

equal another column's values if the first column's value is NA in this row

Could you please try following and let me know if this helps you.

df21223$B[is.na(df21223$B[1])] <- df21223$A

Output will be as follows for data frame's B part:

> df21223$B
[1]  3 NA NA  5 NA NA  7

Where Sample data is:

> df21223$A
[1]  3 NA NA  5 NA NA  7
> df21223$B
[1] NA NA NA NA NA NA NA
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93