Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign() to specific indices of vectors, vectors specified by string names

I’m trying to assign values to specific indices of a long list of vectors (in a loop), where each vector is specified by a string name. The naive approach

testVector1 <- c(0, 0, 0)

vectorName <- "testVector1"
indexOfInterest <- 3

assign(x = paste0(vectorName, "[", indexOfInterest, "]"), value = 1)

doesn’t work, instead it creates a new vector "testVector1[3]" (the goal was to change the value of testVector1 to c(0, 0, 1)).

I know the problem is solvable by overwriting the whole vector:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

temporaryVector <- get(x = vectorName)
temporaryVector[indexOfInterest] <- 1
assign(x = vectorName, value = temporaryVector)

but I was hoping for a more direct approach.

Is there some alternative to assign() that solves this?

Similarly, is there a way to assign values to specific elements of columns in data frames, where both the data frames and columns are specified by string names?

>Solution :

If you must do this you can do it with eval(parse():

valueToAssign  <- 1
stringToParse  <- paste0(
    vectorName, "[", indexOfInterest, "] <- ", valueToAssign
)
eval(parse(text = stringToParse))

testVector1
# [1] 0 0 1

But this is not recommended. Better to put the desired objects in a named list, e.g.:

testVector1 <- c(0, 0, 0)

dat  <- data.frame(a = 1:5, b = 2:6)

l  <- list(
    testVector1 = testVector1,
    dat = dat
)

Then you can assign to them by name or index:


vectorName <- "testVector1"
indexOfInterest <- 3

dfName  <- "dat"
colName  <- "a"
rowNum  <- 3

valueToAssign  <- 1

l[[vectorName]][indexOfInterest]  <- valueToAssign
l[[dfName]][rowNum, colName]  <- valueToAssign

l
# $testVector1
# [1] 0 0 1

# $dat
#   a b
# 1 1 2
# 2 2 3
# 3 1 4
# 4 4 5
# 5 5 6
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading