【问题标题】:Unexpected output from map of list column列表列映射的意外输出
【发布时间】:2021-05-18 00:16:24
【问题描述】:

下面是我的代码的输出,以及我想要的输出。我只希望打印出每个字符向量,但是它会打印两个字符向量,然后还会打印出整个列表列。为什么会发生这种情况,我应该改变什么来获得我想要的输出?

library(tidyverse)

data <- tribble(
  ~x,  ~y,
  "a", rep("yes", 10),
  "b", rep("no", 10)
)

map(data$y, ~ print(.x))
#>  [1] "yes" "yes" "yes" "yes" "yes" "yes" "yes" "yes" "yes" "yes"
#>  [1] "no" "no" "no" "no" "no" "no" "no" "no" "no" "no"
#> [[1]]
#>  [1] "yes" "yes" "yes" "yes" "yes" "yes" "yes" "yes" "yes" "yes"
#> 
#> [[2]]
#>  [1] "no" "no" "no" "no" "no" "no" "no" "no" "no" "no"

期望的输出:

#>  [1] "yes" "yes" "yes" "yes" "yes" "yes" "yes" "yes" "yes" "yes"
#>  [1] "no" "no" "no" "no" "no" "no" "no" "no" "no" "no"

reprex package (v1.0.0) 于 2021-02-14 创建

【问题讨论】:

    标签: r dplyr nested tidyverse tibble


    【解决方案1】:

    lapply/map 将始终返回一个值。所以你告诉它print这个值,它还返回传递的值,所以你得到两个输出。因此,您只需使用.x 即可获得其中之一。

    purrr::map(data$y, ~ .x)
    

    相同
    data$y
    

    【讨论】:

      猜你喜欢
      • 2021-12-08
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2018-12-13
      • 2014-08-13
      • 2018-10-16
      相关资源
      最近更新 更多