Skip to content
Back to formatted view

Raw Message

Message-ID: <20210409144357.06211e46@arachnoid>
Date: 2021-04-09T11:43:57Z
From: Ivan Krylov
Subject: Assigning several lists to variables whose names are contained in other variables
In-Reply-To: <557f5c83-003f-4406-a717-c8a2c3f160ff@numberland.de>

Dear Wolfgang,

On Fri, 9 Apr 2021 11:48:55 +0200
Wolfgang Grond <grond at numberland.de> wrote:

> I want to assign the subnets to variables whose names contain the
> name of the subnet

Apologies if this sounds too opinionated, but creating variable names
from variable values is a FAQ in a different dynamic language:

https://perldoc.perl.org/perlfaq7#How-can-I-use-a-variable-as-a-variable-name?

Most of the explanation doesn't apply to R, of course, but the main
idea here is to use data structures instead of causing (potential,
unlikely, but still) conflicts in the variable namespace. What if you
create a list of function values instead of just a bunch of variables?

results <- list()
for(i in 1:nrow(datatable)) {
	val <- datatable$column[i]
	results[[as.character(val)]] <- my_function(val)
}

Or even

results <- lapply(setNames(nm = datatable$column), my_function)

Wouldn't that be more convenient?

-- 
Best regards,
Ivan