Home > Net >  map does not work on vector which i am trying to use
map does not work on vector which i am trying to use

Time:01-30

I have the data as below

adsl <- structure(list(SUBGRPVAR1 = structure(c("F", "M", "M", "M", "F", 
"F"), label = "Sex"), SUBGRPVAR2 = structure(c("Y", "N", "Y", 
"N", "Y", "N"), label = "Completers of Week 8 Population Flag")), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

# A tibble: 6 × 2
  SUBGRPVAR1 SUBGRPVAR2
  <chr>      <chr>     
1 F          Y         
2 M          N         
3 M          Y         
4 M          N         
5 F          Y         
6 F          N         

which i would like to change to as below

# A tibble: 6 × 2
  SUBGRPVAR1 SUBGRPVAR2
  <chr>      <chr>     
1 Total      Total     
2 Total      Total     
3 Total      Total     
4 Total      Total     
5 Total      Total     
6 Total      Total     
  

I would like to use the below map with the vector subgrpvarc, however when i do I get the error as object .x not found, i am not sure why it is not work. Please advice

subgrpvarc <- c("SUBGRPVAR1", "SUBGRPVAR2")

map(subgrpvarc, ~ adsl[[names(adsl)[match(.x, names(adsl))]]] <- 'Total')

CodePudding user response:

I'm not sure if that was a good example for requesting the use of map. Here is a much simple way to accomplish the same thing:

adsl[subgrpvarc] <- 'Total'

So I suppose you could say that "[<-" is implicitly "mapping" when given multiple column names. The "[[" function cannot take multiple arguments. If you try to give "[[" a vector of length greater than 1 it errors out:

adsl[[subgrpvarc]]
#----------------
Error in `vectbl_as_col_location2()`:
! Can't extract column with `subgrpvarc`.
  • Related