Hank Lin
Hank Lin

Reputation: 6479

Is there a better way to replace columns of one dataframe with those of another in R?

I have two dataframes, one is a subset of the other (but with different values).

iris
iris2 <- iris[1:2]

I want to replace columns of the first dataframe with the different values of the other

iris <- iris %>% mutate(Sepal.Length = iris2$Sepal.Length,
               Sepal.Width = iris2$Sepal.Width)

Is there a way to write this code more elegantly (eg with purrr)?

Upvotes: 0

Views: 42

Answers (1)

socialscientist
socialscientist

Reputation: 4232

Depending upon assumptions we can make about the two data.frames, different options are available. I'll call the original data.frame df1 and the one you want to use to replace its columns df2.

Pick your poison! I like the base R solutions.

df2 only contains columns to replace in df1

# Example data
df1 <- data.frame(x = rep(1,2), y = rep(2,2), z = rep(3,2))
df2 <- data.frame(x = rep(4,2), y = rep(5,2))

# Base R
df1[, colnames(df2)] <- df2

# dplyr
library(dplyr)

df1 %>%
  select(-colnames(df2)) %>%
  cbind(df2)

df2 contains additional columns

# data
df1 <- data.frame(x = rep(1,2), y = rep(2,2), z = rep(3,2))
df2 <- data.frame(x = rep(4,2), y = rep(5,2), w = rep(6,2))

# used for all answers
common <- intersect(names(df1), names(df2))

# base r
df1[ , common] <- df2[, common]

# dplyr1
df1[ , common] <- df2 %>%
                 select(all_of(common))

# dplyr2
df1 %>%
  select(-all_of(common)) %>%
  cbind(., df2 %>% select(all_of(common)))
 
# dplyr3
df1 %>%
  select(-all_of(common)) %>%
  cbind(., df2[ , common])

Upvotes: 1

Related Questions