如何将字符串而非实时数字指定为给定特定数据框的值?
问题描述:
(再现的示例中所示)的功能如下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)。如何实现这一目标?
同样地,如何列出组合与字符串而非数字
答
我们可以更新与串矢量通过位置相匹配的名字列:
# update columns with matching name
df1$from <- c("inf", "gdp", "exc", "stock")[df1$from]
df1$to <- c("inf", "gdp", "exc", "stock")[df1$to]
# result
df1
# from to pval
# 1 inf gdp 0.5
# 2 inf exc 0.6
# 3 inf stock 0.1
# 4 gdp inf 0.4
# 5 gdp exc 0.8
# 6 gdp stock 0.2
# 7 exc inf 0.1
# 8 exc gdp 0.5
# 9 exc stock 0.9
# 10 stock inf 0.0
# 11 stock gdp 0.0
# 12 stock exc 0.1
# input data
df1 <- read.table(text=" 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", header = TRUE)
“将数字转换成VAR的名字” - 'df1 $ fromNew zx8754
@ zx8754你解决了!您可以将其添加为答案:df1