1

I'm looking to tack on a bunch of variables to an existing dataframe, based on another dataframe. I was using this question and answer to set myself up, but it's not actually doing anything.

Let's say in the code below I have a dataframe named comp, and I want to add to the dataframe iris empty variables by iteratively going through each column in comp and naming that variable by the first row in the column "vs" the second row in that column:

library(tidyverse)
comp <- as_tibble(combn(letters[1:4], 2))
mydf <- as_tibble(iris)

# Creating a function that creates a variable name for each column in comp
# and creates a variable with that name in df
varname_assign <- function(df, n){
varname <- paste0(comp[[1,n]], "Vs", comp[[2,n]])
mutate_(df, .dots= setNames(list(NA), varname))
return(df)
}

for (i in seq_along(comp)) {
mydf <- varname_assign(mydf, i)
}

mydf

# A tibble: 150 × 5
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
      <dbl>       <dbl>        <dbl>       <dbl>  <fctr>
1      5.1         3.5          1.4         0.2  setosa

#Nothing happened :(

I'm trying to get something like this:

# A tibble: 150 × 11
Sepal.Length Sepal.Width Petal.Length Petal.Width Species  AvsB  AvsC  AvsD  BvsC  BvsD  CvsD
      <dbl>       <dbl>        <dbl>       <dbl>  <fctr>  <lgl> <lgl> <lgl> <lgl> <lgl> <lgl>
1      5.1         3.5          1.4         0.2  setosa    NA    NA    NA    NA    NA    NA

EDIT: sigh. I just realized return(df) in the function is the culprit. If I remove that line, it all works. Not sure what the logic is behind that, though.

Community
  • 1
  • 1
Phil
  • 4,424
  • 3
  • 22
  • 55

0 Answers0