1

I have this dataframe

 # of int. int. not.int. ID group odd even 2 24 85.15 113.34 2 thc1 NA 486.66 3 33 134.94 158.17 3 thc2 465.06 NA 4 12 47.60 62.73 4 thc3 NA 537.27 1 50 218.41 372.16 1 veh 381.59 NA 5 44 176.81 268.92 5 veh NA 331.08 

How can I replace the numbers in 'int.' with the numbers in 'even' without adding the NA's and the same for 'odd' and 'not.int'? So it would look like this.

 # of int. int. not.int. ID group odd even 2 24 486.66 113.34 2 thc1 NA 486.66 3 33 134.94 465.06 3 thc2 465.06 NA 4 12 537.27 62.73 4 thc3 NA 537.27 1 50 218.41 381.59 1 veh 381.59 NA 5 44 331.08 268.92 5 veh NA 331.08 

4 Answers 4

3

One option is to use Map in base R to get the corresponding columns and then do an assignment

df1[2:3] <- Map(function(x, y) { i1 <- !is.na(y) x[i1] <- y[i1] x}, df1[c('int.', 'not.int.')], df1[c('even', 'odd')]) df1 # # of int. int. not.int. ID group odd even #2 24 486.66 113.34 2 thc1 NA 486.66 #3 33 134.94 465.06 3 thc2 465.06 NA #4 12 537.27 62.73 4 thc3 NA 537.27 #1 50 218.41 381.59 1 veh 381.59 NA #5 44 331.08 268.92 5 veh NA 331.08 

data

 df1 <- structure(list(`# of int.` = c(24L, 33L, 12L, 50L, 44L), int. = c(85.15, 134.94, 47.6, 218.41, 176.81), not.int. = c(113.34, 158.17, 62.73, 372.16, 268.92), ID = c(2L, 3L, 4L, 1L, 5L), group = c("thc1", "thc2", "thc3", "veh", "veh"), odd = c(NA, 465.06, NA, 381.59, NA), even = c(486.66, NA, 537.27, NA, 331.08)), .Names = c("# of int.", "int.", "not.int.", "ID", "group", "odd", "even"), class = "data.frame", row.names = c("2", "3", "4", "1", "5")) 
Sign up to request clarification or add additional context in comments.

Comments

2

Using mutate and ifelse from the dplyr package :

library(dplyr) df %>% mutate(int. = ifelse(is.na(even), int., even), not.int. = ifelse(is.na(odd), not.int., odd)) 

Comments

1

Here is an option in base R, with ifelse and is.na.

dat$int <- with(dat, ifelse(!is.na(even), even, int)) dat$not.int <- with(dat, ifelse(!is.na(odd), odd, not.int)) 

DATA

dat <- read.table(text = " '# of int' int 'not.int' ID group odd even 2 24 85.15 113.34 2 thc1 NA 486.66 3 33 134.94 158.17 3 thc2 465.06 NA 4 12 47.60 62.73 4 thc3 NA 537.27 1 50 218.41 372.16 1 veh 381.59 NA 5 44 176.81 268.92 5 veh NA 331.08", header = TRUE, stringsAsFactors = FALSE) 

Comments

1
x <- df1[c("even","odd")] df1[c("int.","not.int.")][!is.na(x)] <- x[!is.na(x)] # # of int. int. not.int. ID group odd even # 2 24 486.66 113.34 2 thc1 NA 486.66 # 3 33 134.94 465.06 3 thc2 465.06 NA # 4 12 537.27 62.73 4 thc3 NA 537.27 # 1 50 218.41 381.59 1 veh 381.59 NA # 5 44 331.08 268.92 5 veh NA 331.08 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.