Merge Data Frame Columns & Remove NAs in R (Example Code)
In this R tutorial you’ll learn how to join data frame columns and remove NA values.
Creating Example Data
my_df <- data.frame(col1 = c(11, NA, NA, NA, 15, NA), # Constructing an example data frame col2 = c(NA, NA, 13, 14, NA, NA), col3 = c(NA, 12, NA, NA, NA, 16), x = letters[1:6]) my_df # col1 col2 col3 x # 1 11 NA NA a # 2 NA NA 12 b # 3 NA 13 NA c # 4 NA 14 NA d # 5 15 NA NA e # 6 NA NA 16 f |
my_df <- data.frame(col1 = c(11, NA, NA, NA, 15, NA), # Constructing an example data frame col2 = c(NA, NA, 13, 14, NA, NA), col3 = c(NA, 12, NA, NA, NA, 16), x = letters[1:6]) my_df # col1 col2 col3 x # 1 11 NA NA a # 2 NA NA 12 b # 3 NA 13 NA c # 4 NA 14 NA d # 5 15 NA NA e # 6 NA NA 16 f
Example: Combining Columns & Remove NAs
my_df_combi <- cbind(new = na.omit(unlist(my_df[ , c("col1", "col2", "col3")])), # Merging columns my_df[ , ! colnames(my_df) %in% c("col1", "col2", "col3"), drop = FALSE]) my_df_combi # new x # col11 11 a # col15 15 b # col23 13 c # col24 14 d # col32 12 e # col36 16 f |
my_df_combi <- cbind(new = na.omit(unlist(my_df[ , c("col1", "col2", "col3")])), # Merging columns my_df[ , ! colnames(my_df) %in% c("col1", "col2", "col3"), drop = FALSE]) my_df_combi # new x # col11 11 a # col15 15 b # col23 13 c # col24 14 d # col32 12 e # col36 16 f
Further Resources & Related Articles
Have a look at the following R tutorials. They discuss topics such as time objects, missing data, and data inspection.