在向量中使用 expand.grid 的组合
Combinations using expand.grid in vector
我想在矢量中使用 expand.grid
以特定格式创建 myvec
中的所有因子组合,并且不重复。我尝试:
myvec <- c("B2","B3","B4","B8","NDVI","SAVI","SIPI","SR","RGI","TVI",
"MSR","PRI","GNDVI","PSRI","GCI")
grid <- expand.grid(c(rep(myvec,length(myvec))), KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE)
grid
# Var1
# 1 B2
# 2 B3
# 3 B4
# 4 B8
# 5 NDVI
但是,不起作用,我想要的输出是:
grid
# Var1
# 1 B2_B3
# 2 B2_B4
# 3 B2_B8
# ...
# last B2_B3_B4_B8_NDVI_SAVI_SIPI_SR_RGI_TVI_MSR_PRI_GNDVI_PSRI_GCI
请问有什么帮助吗?
如果我们需要为从 2 到 'myvec' 的 length
的组合创建单个字符串,请使用 combn
grid <- data.frame(Var1 = unlist(lapply(2:length(myvec), \(i)
combn(myvec, i, FUN = paste, collapse = "_"))))
-输出
> head(grid)
Var1
1 B2_B3
2 B2_B4
3 B2_B8
4 B2_NDVI
5 B2_SAVI
6 B2_SIPI
> tail(grid)
Var1
32747 B2_B3_B4_B8_SAVI_SIPI_SR_RGI_TVI_MSR_PRI_GNDVI_PSRI_GCI
32748 B2_B3_B4_NDVI_SAVI_SIPI_SR_RGI_TVI_MSR_PRI_GNDVI_PSRI_GCI
32749 B2_B3_B8_NDVI_SAVI_SIPI_SR_RGI_TVI_MSR_PRI_GNDVI_PSRI_GCI
32750 B2_B4_B8_NDVI_SAVI_SIPI_SR_RGI_TVI_MSR_PRI_GNDVI_PSRI_GCI
32751 B3_B4_B8_NDVI_SAVI_SIPI_SR_RGI_TVI_MSR_PRI_GNDVI_PSRI_GCI
32752 B2_B3_B4_B8_NDVI_SAVI_SIPI_SR_RGI_TVI_MSR_PRI_GNDVI_PSRI_GCI
我想在矢量中使用 expand.grid
以特定格式创建 myvec
中的所有因子组合,并且不重复。我尝试:
myvec <- c("B2","B3","B4","B8","NDVI","SAVI","SIPI","SR","RGI","TVI",
"MSR","PRI","GNDVI","PSRI","GCI")
grid <- expand.grid(c(rep(myvec,length(myvec))), KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE)
grid
# Var1
# 1 B2
# 2 B3
# 3 B4
# 4 B8
# 5 NDVI
但是,不起作用,我想要的输出是:
grid
# Var1
# 1 B2_B3
# 2 B2_B4
# 3 B2_B8
# ...
# last B2_B3_B4_B8_NDVI_SAVI_SIPI_SR_RGI_TVI_MSR_PRI_GNDVI_PSRI_GCI
请问有什么帮助吗?
如果我们需要为从 2 到 'myvec' 的 length
的组合创建单个字符串,请使用 combn
grid <- data.frame(Var1 = unlist(lapply(2:length(myvec), \(i)
combn(myvec, i, FUN = paste, collapse = "_"))))
-输出
> head(grid)
Var1
1 B2_B3
2 B2_B4
3 B2_B8
4 B2_NDVI
5 B2_SAVI
6 B2_SIPI
> tail(grid)
Var1
32747 B2_B3_B4_B8_SAVI_SIPI_SR_RGI_TVI_MSR_PRI_GNDVI_PSRI_GCI
32748 B2_B3_B4_NDVI_SAVI_SIPI_SR_RGI_TVI_MSR_PRI_GNDVI_PSRI_GCI
32749 B2_B3_B8_NDVI_SAVI_SIPI_SR_RGI_TVI_MSR_PRI_GNDVI_PSRI_GCI
32750 B2_B4_B8_NDVI_SAVI_SIPI_SR_RGI_TVI_MSR_PRI_GNDVI_PSRI_GCI
32751 B3_B4_B8_NDVI_SAVI_SIPI_SR_RGI_TVI_MSR_PRI_GNDVI_PSRI_GCI
32752 B2_B3_B4_B8_NDVI_SAVI_SIPI_SR_RGI_TVI_MSR_PRI_GNDVI_PSRI_GCI