使用列名展开所有列
expand all columns using column names
我想获取数据框中所有列值的所有可能组合,例如
library(tidyr)
# example data
fruits <- tibble(
type = c("apple", "orange", "banana"),
year = c(2010, 2011, 2012),
size = c("XS", "S", "M"),
weights = rnorm(3, 2)
)
# this works
expand(fruits, type, year, size, weights)
但在我的真实数据框中,我想扩展很多列,并且 i) 不想手动输入所有列名,并且 ii) 并不总是提前知道列名。我希望这会起作用,但它不起作用。
expand(fruits, names(fruits))
有没有办法使用 names()
之类的东西来自动展开所有列?
do.call(expand, c(list(fruits), lapply(names(fruits), as.symbol)))
# # A tibble: 81 x 4
# type year size weights
# <chr> <dbl> <chr> <dbl>
# 1 apple 2010 M 0.994
# 2 apple 2010 M 2.25
# 3 apple 2010 M 2.34
# 4 apple 2010 S 0.994
# 5 apple 2010 S 2.25
# 6 apple 2010 S 2.34
# 7 apple 2010 XS 0.994
# 8 apple 2010 XS 2.25
# 9 apple 2010 XS 2.34
# 10 apple 2011 M 0.994
# # ... with 71 more rows
我想获取数据框中所有列值的所有可能组合,例如
library(tidyr)
# example data
fruits <- tibble(
type = c("apple", "orange", "banana"),
year = c(2010, 2011, 2012),
size = c("XS", "S", "M"),
weights = rnorm(3, 2)
)
# this works
expand(fruits, type, year, size, weights)
但在我的真实数据框中,我想扩展很多列,并且 i) 不想手动输入所有列名,并且 ii) 并不总是提前知道列名。我希望这会起作用,但它不起作用。
expand(fruits, names(fruits))
有没有办法使用 names()
之类的东西来自动展开所有列?
do.call(expand, c(list(fruits), lapply(names(fruits), as.symbol)))
# # A tibble: 81 x 4
# type year size weights
# <chr> <dbl> <chr> <dbl>
# 1 apple 2010 M 0.994
# 2 apple 2010 M 2.25
# 3 apple 2010 M 2.34
# 4 apple 2010 S 0.994
# 5 apple 2010 S 2.25
# 6 apple 2010 S 2.34
# 7 apple 2010 XS 0.994
# 8 apple 2010 XS 2.25
# 9 apple 2010 XS 2.34
# 10 apple 2011 M 0.994
# # ... with 71 more rows