1
(再現的示例中所示)的功能如下causfinder::causalitycombinations
:如何將字符串而非實時數字指定爲給定特定數據框的值?
causalitycombinations <- function (nvars, ncausers, ndependents)
{
independents <- combn(nvars, ncausers)
swingnumber <- dim(combn(nvars - ncausers, ndependents))[[2]]
numberofallcombinations <- dim(combn(nvars, ncausers))[[2]] * swingnumber
dependents <- matrix(, nrow = dim(combn(nvars, ncausers))[[2]] * swingnumber, ncol = ndependents)
for (i in as.integer(1:dim(combn(nvars, ncausers))[[2]])) {
dependents[(swingnumber * (i - 1) + 1):(swingnumber * i), ] <- t(combn(setdiff(seq(1:nvars), independents[, i]), ndependents))
}
swingedindependents <- matrix(, nrow = dim(combn(nvars, ncausers))[[2]] * swingnumber, ncol = ncausers)
for (i in as.integer(1:dim(combn(nvars, ncausers))[[2]])) {
for (j in as.integer(1:swingnumber)) {
swingedindependents[(i - 1) * swingnumber + j, ] <- independents[, i]
}
}
independentsdependents <- cbind(swingedindependents, dependents)
others <- matrix(, nrow = dim(combn(nvars, ncausers))[[2]] * swingnumber, ncol = nvars - ncausers - ndependents)
for (i in as.integer(1:((dim(combn(nvars, ncausers))[[2]]) *
swingnumber))) {
others[i, ] <- setdiff(seq(1:nvars), independentsdependents[i, ])
}
causalitiestemplate <- cbind(independentsdependents, others)
causalitiestemplate
}
列出了所有的多元因果關係的組合。例如,在一個4變量系統中,以系統的其他兩個變量爲條件,它們是(當變量被分配到數字1,2,3,4並且該分配在整個分析過程中保持):
causalitycombinations(4,1,1)
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 1 3 2 4
[3,] 1 4 2 3
[4,] 2 1 3 4
[5,] 2 3 1 4
[6,] 2 4 1 3 # to check whether 2nd var Grangercauses 4th var condioned on 1 and 3
[7,] 3 1 2 4
[8,] 3 2 1 4
[9,] 3 4 1 2
[10,] 4 1 2 3
[11,] 4 2 1 3
[12,] 4 3 1 2
現在,
data.frame(from = causalitycombinations(4,1,1)[,1], to= causalitycombinations(4,1,1)[,2],
pval = c(0.5,0.6,0.1, #I just typed random p-vals here
0.4,0.8,0.2,
0.1,0.5,0.9,
0.0,0.0,0.1)
)
生產:
from to pval
1 1 2 0.5
2 1 3 0.6
3 1 4 0.1
4 2 1 0.4
5 2 3 0.8
6 2 4 0.2
7 3 1 0.1
8 3 2 0.5
9 3 4 0.9
10 4 1 0.0
11 4 2 0.0
12 4 3 0.1
在上述 「從」 和 「到」 列的條目,我想打印變量的名字(比如:「inf」,「gdp」,「exc」,「stock」)而不是他們的代表號碼(即1,2,3,4)。如何實現這一目標?
同樣地,如何列出組合與字符串而非數字
「將數字轉換成VAR的名字」 - 'df1 $ fromNew < - c(「inf」,「gdp」,「exc」,「stock」)[df1 $ from]; df1 $ toNew < - c(「inf」,「gdp」,「exc」,「stock」)[df1 $ to]',我不明白你最後一句話。 – zx8754
@ zx8754你解決了!您可以將其添加爲答案:df1 < - data.frame(from = causalitycombinations(4,1,1)[,1],to = causalitycombinations(4,1,1)[,2], pval = c( 0.5,0.6,0.1,#我剛剛輸入隨機對丘壑這裏 0.4,0.8,0.2, 0.1,0.5,0.9, 0.0,0.0,0.1)) DF1 $ fromNew < - C( 「INF」,「 gdp「,」exc「,」stock「)[df1 $ from]; df1 $ toNew < - c(「inf」,「gdp」,「exc」,「stock」)[df1 $ to] df1 [c(「fromNew」,「toNew」,「pval」)] –