我想獲得資料框中所有列值的所有可能組合,例如
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(), 來自動擴展所有列?
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/450203.html
上一篇:如何從R中的字串中獲取前n個字符
