简体   繁体   中英

How to map column names inside another (p)map function

I'd like to change each value in mydf2 to its closest value in attitude 's corresponding column. For example we replace the first value in mydf2 's complaints column, 64.37888, with 64 since 64 is the nearest number in attitude 's complaints column. This should be easy enough, except I'd like the code to generalize to many column names. Whereas there are only three columns of interest in the example below, I'd like the code to also work if just add "raises" or "critical" to the end of the vector cols_to_iterate .

library(tidyverse)
library(DescTools)
set.seed(123)
cols_to_iterate <- c("complaints", "learning", "advance")
mydf2 <- as.data.frame(map(attitude[cols_to_iterate], ~runif(6, 50, 100)))

map(cols_to_iterate, function(col_of_interest){
  pmap(mydf2, function(cols_to_iterate, ...){
    new_mydf2_col_val <- Closest(pull(attitude, col_of_interest), col_of_interest)
    return(new_mydf2_col_val)
  })
}
)

# Error in x - a : non-numeric argument to binary operator

I tried the above code, but the pmap anonymous function isn't recognizing cols_to_iterate as an input the same way as if I had manually entered function(c("complaints, "learning", advance")).

Thank you!

You shouldn't use pmap here as pmap is used for iterating through rows. You should use map instead.

library(tidyverse)
library(DescTools)
set.seed(123)
cols_to_iterate <- c("complaints", "learning", "advance")
mydf2 <- as.data.frame(map(attitude[cols_to_iterate], ~runif(6, 50, 100)))

map2_df(mydf2,colnames(mydf2),function(column,colname){
    map_dbl(column,function(cell){
        Closest(attitude[[colname]],cell)[1] # use the first value in case there are two closest values
    })
})

# A tibble: 6 x 3
  complaints learning advance
       <dbl>    <dbl>   <dbl>
1         64       75      72
2         90       75      72
3         70       75      55
4         90       72      72
5         90       75      63
6         53       72      52

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM