简体   繁体   English

在R中分配功能的替代方法

[英]Alternative to assign function in r

I am using the following code in a loop, I am just replicating the part which I am facing the problem in. The entire code is extremely long and I have removed parts which are running fine in between these lines. 我在循环中使用以下代码,我只是在复制遇到问题的部分。整个代码非常长,我删除了在这两行之间运行良好的部分。 This is just to explain the problem: 这只是为了说明问题:

    for (j in 1:2)
     {
      assign(paste("numeric_data",j,sep="_"),unique_id)
      for (i in 1:2)
      {
       assign(paste("numeric_data",j,sep="_"), 
              merge(eval(as.symbol(paste("numeric_data",j,sep="_"))),
              eval(as.symbol(paste("sd_1",i,sep="_"))),all.x = TRUE))
       }
      }

The problem that I am facing is that instead of assign in the second step, I want to use (eval+paste) 我面临的问题是,我想使用(eval + paste)而不是第二步中的分配

    for (j in 1:2)
     {
      assign(paste("numeric_data",j,sep="_"),unique_id)
      for (i in 1:2)
      {
       eval(as.symbol((paste("numeric_data",j,sep="_"))))<- 
              merge(eval(as.symbol(paste("numeric_data",j,sep="_"))),
              eval(as.symbol(paste("sd_1",i,sep="_"))),all.x = TRUE)
       }
      }

However R does not accept eval while assigning new variables. 但是,R在分配新变量时不接受eval。 I looked at the forum and everywhere assign is suggested to solve the problem. 我在论坛上看了看,到处都建议分配作业来解决问题。 However, if I use assign the loop overwrites my previously generated "numeric_data" instead of adding to it, hence I get output for only one value of i instead of both. 但是,如果我使用assign,则该循环将覆盖之前生成的“ numeric_data”而不是将其添加到其中,因此,我仅获得i的一个值而不是两个值的输出。

Here is a very basic intro to one of the most fundamental data structures in R. I highly recommend reading more about them in standard documentation sources. 这是R中最基本的数据结构之一的非常基本的介绍。我强烈建议在标准文档来源中阅读有关它们的更多信息。

#A list is a (possible named) set of objects
numeric_data <- list(A1 = 1, A2 = 2)
#I can refer to elements by name or by position, e.g. numeric_data[[1]]
> numeric_data[["A1"]]
[1] 1

#I can add elements to a list with a particular name 
> numeric_data <- list()
> numeric_data[["A1"]] <- 1
> numeric_data[["A2"]] <- 2
> numeric_data
$A1
[1] 1

$A2
[1] 2

#I can refer to named elements by building the name with paste() 
> numeric_data[[paste0("A",1)]]
[1] 1

#I can change all the names at once... 
> numeric_data <- setNames(numeric_data,paste0("B",1:2))
> numeric_data
$B1
[1] 1

$B2
[1] 2

#...in multiple ways 
> names(numeric_data) <- paste0("C",1:2)
> numeric_data
$C1
[1] 1

$C2
[1] 2

Basically, the lesson is that if you have objects with names with numeric suffixes: object_1 , object_2 , etc. they should almost always be elements in a single list with names that you can easily construct and refer to. 基本上,该课程是,如果您具有名称带有数字后缀的对象: object_1object_2等,它们几乎应始终是单个列表中的元素,并且具有可以轻松构造和引用的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM