3

我也有嵌套在带有标识符列的列表中的小标题。我想在每个嵌套的 tibble 上运行匿名函数。但是,当我使用管道引用我的主 df 然后引用包含我的数据映射的列表时不起作用。

# Creating the df
df_nested <- iris %>% group_by(Species) %>% nest()

# Does not work
# df_nested %>% 
# map(data, nrow)

# Works
map(df_nested$data, nrow)

我想了解为什么代码不能使用管道。

4

2 回答 2

2

mutate使用数据时总是更好地使用nested

df_nested %>% 
   mutate(Nrow=map(data,nrow)) %>% 
   unnest(Nrow)
# A tibble: 3 x 3
  Species    data               Nrow
  <fct>      <list>            <int>
1 setosa     <tibble [50 x 4]>    50
2 versicolor <tibble [50 x 4]>    50
3 virginica  <tibble [50 x 4]>    50
于 2019-06-01T13:00:02.787 回答
2

这是因为当使用管道 ( %>%) 时,默认情况下第一个参数是从 LHS 传递的。

当你在做

df_nested %>% map(data, nrow)

你得到

#$Species
#[1] ".x[[i]]" "nrow"   

#$data
#[1] ".x[[i]]" "nrow"   

#Warning messages:
#1: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
#2: In .f(.x[[i]], ...) : data set ‘nrow’ not found
#3: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
#4: In .f(.x[[i]], ...) : data set ‘nrow’ not found

这与

map(df_nested, data, nrow)

如果你想使用管道,你可能需要

df_nested$data %>% map(nrow)

#[[1]]
#[1] 50

#[[2]]
#[1] 50

#[[3]]
#[1] 50
于 2019-06-01T12:04:46.983 回答