简体   繁体   English

如何在另一个(p)映射函数中映射列名

[英]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. 我想在每个值更改mydf2在其最接近的价值attitude的相应列。 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. 例如,我们将mydf2complaints列中的第一个值mydf2替换为64,因为64是attitudecomplaints列中最接近的数字。 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 . 尽管在下面的示例中只有三列需要关注,但是我希望代码也可以在矢量cols_to_iterate的末尾添加“ raises”或“ critical”来使用。

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")). 我尝试了上面的代码,但pmap匿名函数无法像手动输入函数一样识别cols_to_iterate作为输入(c(“投诉,”学习“,”高级“))。

Thank you! 谢谢!

You shouldn't use pmap here as pmap is used for iterating through rows. 您不应在此处使用pmap ,因为pmap用于遍历行。 You should use map instead. 您应该改用map

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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