简体   繁体   中英

combine only values across two columns in r

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!

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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM