Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 消除附加字符向量的循环_R_Loops_Vector - Fatal编程技术网

R 消除附加字符向量的循环

R 消除附加字符向量的循环,r,loops,vector,R,Loops,Vector,我是超级新手,但有一些在EViews中编码的经验。从我在这个网站上读到的帖子中,我了解到循环通常可以被R中更快的代码所取代。 所以,我的问题是:我试图得到R中的字符向量。每个“字符”将是一个变量名,由一个国家代码和一个变量组成。 如果我有两个国家和三个变量,我需要一个2x3=6个字符的向量。 这是我想出的代码: list_pgo=character(0) for (y in allb){ ###concept code a b c for (x in cty){ ###country code

我是超级新手,但有一些在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   
}
} 
list\u pgo=字符(0)
对于(y在allb){####概念代码abc
对于(x in cty){####美国国家代码

tempb以下功能应该可以满足您的需要。R中的许多函数已经进行了向量化(例如
粘贴
),这意味着它们接受向量,并在向量长度不匹配时使用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"
#定义玩具数据(作为字符向量)

全部B或一行:
apply(expand.grid(x,y),1,function(x)paste(x[1],“pgo”,x[2],“_id”,sep=”“)
@ulfeld当然可以,但我发现代码不太容易理解(特别是对于刚接触R的人)。更不用说,我还认为它在几乎所有情况下都比较慢。请参阅编辑。
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