我对 R 非常陌生,但有一些在 EViews 中编码的经验。从我在这个网站上阅读的帖子中,我了解到循环通常可以被 R 中更快的代码取代。 所以,这是我的问题:我正在尝试获取 R 中的字符向量。每个“字符”都是一个由国家/地区代码和变量组成的变量名称。 因此,如果我有两个国家和三个变量,我需要一个 2x3=6 个字符的向量。 这是我想出的代码:
list_pgo=character(0)
for (y in allb){ ###concept code a b c
for (x in cty){ ###country code fr us
tempb <- paste(x,"pgo",y,"_id",sep="") ##variable name should be xpgoy_id
list_pgo<-append(list_pgo,tempb,after=length(list_pgo)) ### result should be something like frpgoa_id uspgoa_id frpgob_id uspgob_id frpgoc_id uspgoc_id
}
}
提前非常感谢您的帮助
最佳答案
以下内容应该可以满足您的要求。 R 中的许多函数已经向量化(例如 paste
),这意味着它们接受向量,并在向量长度不匹配时使用 R 的通常重用/重复规则执行逐元素操作。
# Define your toy data (as character vectors)
allb <- c("a", "b", "c")
cty <- c("fr", "us")
# Get all combinations
all.comb <- expand.grid(x = allb, y = cty)
# Combine columns of generated matrix
list_pgo <- paste0(all.comb$x, "pgo", all.comb$y, "_id")
print(list_pgo)
#[1] "apgofr_id" "bpgofr_id" "cpgofr_id" "apgous_id" "bpgous_id" "cpgous_id"
编辑:当然还存在其他方式和方法,但是已经矢量化的函数通常比只能被视为“循环隐藏”的 apply-family 函数快得多。
将上面的内容与评论中的一行进行比较:
library("microbenchmark")
fun1 <-function() {
all.comb <- expand.grid(x = allb, y= cty)
paste0(all.comb$x,"pgo",all.comb$y,"_id")
}
fun2 <- function() {
apply(expand.grid(allb,cty), 1, function(x) paste(x[1],"pgo",x[2],"_id",sep=""))
}
microbenchmark(fun1(), fun2())
#Unit: microseconds
# expr min lq mean median uq max neval
# fun1() 88.80 136.7705 185.3204 150.1570 163.098 3722.469 100
# fun2() 246.32 286.9275 353.2598 305.8925 326.419 4920.156 100
关于r - 摆脱附加字符向量的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44944488/