Reputation: 647
I have an issue with the following -
I have a dataframe as below:
I want to move the values from df$C into df$A.
I include df$B here as df$C only contains a value when df$B contains a string.
A B C
1234 NA NA
NA start 1500
2000 NA NA
NA end 2500
NA NA NA
NA NA NA
NA start 3000
So, the desired result is as follows:
A
1234
1500
2000
2500
NA
NA
3000
I'd really appreciate your help with this!
Upvotes: 2
Views: 177
Reputation: 55420
Try:
df$A[is.na(df$A)] <- df$C[is.na(df$A)]
This is selecting from df$A
those values where it is NA
and "fills" them with values from df$C
at the same index.
Upvotes: 4
Reputation: 89097
Use ifelse
. Depending on how you want to process cases where you have non-NA
values for both A
and C
, it will be one of:
df$A <- ifelse(is.na(df$A), df$C, df$A)
or
df$A <- ifelse(is.na(df$C), df$A, df$C)
A couple variants so you don't use too many df$
:
df$A <- with(df, ifelse(is.na(A), C, A)
or
df <- transform(df, A = ifelse(is.na(A), C, A))
Upvotes: 4