0

I have to run 10's of different permutations with same structure but different base names for the output. to avoid having to keep replacing the whole character names within each formula, I was hoping to great a variable then use paste function to assign the variable to the name of the output..

Example:

var<-"Patient1"
(paste0("cells_", var, sep="") <- WhichCells(object=test, expression = test > 0, idents=c("patient1","patient2"))

The expected output would be a variable called "cells_Patient1" Then for subsequent runs, I would just copy and paste these 2 lines and change var <-"Patient1" to var <-"Patient2" [please note that I am oversimplifying the above step of WhichCells as it entails ~10 steps and would rather not have to replace "Patient1" by "Patient2" using Search and Replaced

Unfortunately, I am unable to crate the variable "cells_Patient1" using the above command. I am getting the following error:

Error in variable(paste0("cells_", var, sep = "")) <- WhichCells(object = test, : target of assignment expands to non-language object

Browsing stackoverflow, I couldn't find a solution. My understanding of the error is that R can't assign an object to a variable that is not a constant. Is there a way to bypass this?

1 Answer 1

1

1) Use assign like this:

var <- "Patient1"
assign(paste0("cells_", var), 3)
cells_Patient1
## [1] 3

2) environment This also works.

e <- .GlobalEnv
e[[ paste0("cells_", var) ]] <- 3
cells_Patient1

3) list or it might be better to make these variables into a list:

cells <- list()
cells[[ var ]] <- 3
cells[[ "Patient1" ]]
## [1] 3

Then we could easily iterate over all such variables. Replace sqrt with any suitable function.

lapply(cells, sqrt)
## $Patient1
## [1] 1.732051
Sign up to request clarification or add additional context in comments.

2 Comments

In regards to 1) assign and 2) environment, I got the same following error Error in paste0("cells_", var) : cannot coerce type 'closure' to vector of type 'character' . As for list, it may not work for me as I have multiple commands for each variable that may make it complicated.
Maybe you forgot to define var. var is also an R function to compute the variance. You can see from the reproducible code in the answer and the output shown there that all three do work. If you are really stuck I suggest you cut down the problem to something reproducible so we can copy and paste it into R and see what the problem is. See the instructions at the top of the r tag page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.