0

I have the following question: How to loop/ map the function below over all "X" variables cotained in the datframe instead of repetation (see below)? Further, I would like to name each vector according to the looped "X" variable (see below).

Thanks.


library("purrr")
library("tidyverse")

loadings <- data.frame(Met = c("Met1", "Met2", "Met3"),
                       Food = c("Fruit", "Nuts", "Eggs"),
                       X1 = c(0.5, 0.1, NA),
                       X2 = c(0.1, NA, 0.8),
                       X3 = c(0.3, 0.9, NA))

tbl_loadings <- function(data, depen_indepen_vars, pcs ) {


loadX <- data %>% select({{depen_indepen_vars}}, {{ pcs }} ) %>% filter({{ pcs }}  != "NA") %>% as_tibble()  %>% mutate(load = paste0({{depen_indepen_vars}}, " (", {{ pcs }}  , "), ", collapse = "")) %>% select(load) %>% pull() %>% unique() %>% drop()

return(loadX)

}

# Instead of:
met_loadX1 <- tbl_loadings(loadings, Met, X1)
met_loadX2 <- tbl_loadings(loadings, Met, X2)
met_loadX3 <- tbl_loadings(loadings, Met, X3)


# map/loop over the data. Output names as above (met_loadX1, met_loadX2, met_loadX3):

Created on 2020-07-04 by the reprex package (v0.3.0)

Jzlia10
  • 49
  • 1
  • 7
  • What is your expected output? And is there a reason you're not binding the input data frames together than then modifing the single merged data frame? – Limey Jul 04 '20 at 15:29

1 Answers1

1

You can pass column names as string.

library(dplyr)
library(purrr)
library(rlang)

tbl_loadings <- function(data, depen_indepen_vars, pcs ) {
   dep <- sym(depen_indepen_vars)
   pcs <- sym(pcs)
   loadX <- data %>% 
            filter(!!pcs != "NA") %>% 
            mutate(load = paste0(!!dep, " (", !!pcs, "), ", collapse = "")) %>% 
            pull(load) %>% unique()
  return(loadX)
}


map(paste0('X', 1:3), tbl_loadings, data = loadings, depen_indepen_vars = "Met")

#[[1]]
#[1] "Met1 (0.5), Met2 (0.1), "

#[[2]]
#[1] "Met1 (0.1), Met3 (0.8), "

#[[3]]
#[1] "Met1 (0.3), Met2 (0.9), "
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks for your answer, but it doesn't work for me. I get an output in which the function itself is returned. – Jzlia10 Jul 04 '20 at 16:05
  • Okay, thank you very much. Now it works. I found the error in the function. It shoud be return(loadX) instead of return(load). Then it works. – Jzlia10 Jul 04 '20 at 16:30
  • Sorry, that was auto-corrected. Updated the answer to return `loadX`. – Ronak Shah Jul 05 '20 at 00:50