Reputation: 133
I want to generate list of tibble from one tibble in the following codes:
tbl = tibble(id=1:10, a = rnorm(10), b = rnorm(10))
tbl_list = c("a", "b") %>% map(~ tbl %>% select(c("id", .)))
The output I want is:
tbl_list
[[1]]
# A tibble: 2 x 2
id a
<int> <dbl>
1 1 -0.704
2 2 -0.917
[[2]]
# A tibble: 2 x 2
id b
<int> <dbl>
1 1 -0.704
2 2 -0.917
However, it shows the error message:
"c("id", .)
must evaluate to column positions or names, not a list"
so it seems that .
is not recognized a character, but a list
Could you tell me how to avoid this error?
Upvotes: 2
Views: 248
Reputation: 388982
You can use .x
to access the element
library(tidyverse)
c("a", "b") %>% map(~ tbl %>% select(c("id", .x)))
#[[1]]
# A tibble: 10 x 2
# id a
# <int> <dbl>
# 1 1 1.42
# 2 2 1.51
# 3 3 -0.385
#...
#[[2]]
# A tibble: 10 x 2
# id b
# <int> <dbl>
# 1 1 1.42
# 2 2 0.100
# 3 3 1.28
#....
You can also use .
but while using it in chain operation .
is referring to the object which is on the left-side of the chain i.e tbl
in this case , hence it returns an error. To use .
one way is
c("a", "b") %>% map(~select(tbl, c('id', .)))
Upvotes: 2