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
  • 7,287
  • 3
  • 36
  • 66
  • 1
    You don't assign the return value of `mutate_`. – Roland Dec 02 '16 at 18:16
  • Your `mutate_` call wasn't assigning a result to anything, so it created new variables and then they just vanished, followed by you telling the function to explicitly return the _original_ `df`. If you had done `df <- mutate_(...)` it probably would have worked as you expected, with the `return()` call. – joran Dec 02 '16 at 18:16
  • 2
    Evidently, I need more coffee before posting bad questions. – Phil Dec 02 '16 at 18:18
  • 3
    You can never go wrong with more coffee. – Tim Goodman Dec 02 '16 at 18:50

0 Answers0