【问题标题】:Assigning list elements to variable name in for loop在for循环中将列表元素分配给变量名
【发布时间】:2021-07-25 19:11:08
【问题描述】:

我有以下名单:

names<-c('continent','city','country','carrier','asn','timezone','ip_routing','connection_type','linespeed','source_1')

我想在以下 for 循环的每次迭代中使用这些名称将它们分配给字符串 'fraud_':

for (i in 1:10){
  
fraud_names[i]<-counter(fraud,colnames(fraud[i]))
}

我该怎么做?

【问题讨论】:

  • 什么是counter函数
  • 这是我之前创建的一个函数。我只关心在每次迭代时将上述元素指定为名称。
  • 你的问题不清楚。
  • assign+ paste?
  • 您要创建列吗?

标签: r loops for-loop


【解决方案1】:

最好保留list

list1 <- setNames(rep(1, length(names)), names)
list2env(list1, .GlobalEnv)

【讨论】:

    【解决方案2】:

    不是 100% 清楚最终目标是什么,而是根据您的评论

    names

    以下内容可能有帮助?

    names <- c("continent", "city")
    newnames <- paste0("a_", names)
    newnames
    [1] "a_continent" "a_city"     
    

    话虽如此,也许您正在寻找:

    names <- c("continent", "city")
    fraud_names <- list() # better: vector(mode='list', length=length(names)) so as to preallocate the size.
    
    
    for (i in names){ 
      fraud_names[paste0('fraud_', i)]<-1 
      } 
    
    fraud_names
    $fraud_continent
    [1] 1
    
    $fraud_city
    [1] 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 2012-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      相关资源
      最近更新 更多