1

I want to use a variable as the df name but cant figure out how. I can do it this way

 'vector2 <- df$columname'

If i want to do it in a loop looking at different data tables i cant do it. vector1 is the names of my data.tables that i want to put the column data into a vector2.

I want the loop to do this

 'vector2 <- one$columname'
 'vector2 <- two$columname'
 'vector2 <- three$columname'

changing the data.table name each time it goes through the loop keeping column name the same.

'vector1<- c("one","two","three")
for(i in vector1) {
vector2 <- vector1$columname
}'
0

1 Answer 1

1

Based on the updated in OP's post, use either mget (returns the values of all the objects into a named list) or get (for a single element - can be used within for loop) to return the values of the dataset names i.e. 'one', 'two', 'three'

lst1 <- lapply(mget(vector1), function(x) x$columname)

If it should be a single vector

vector2 <- unlist(lst1)

In a for loop, it can be done as

for(i in vector1) vector2 <- get(i)$columname

This replaces 'vector2' in each iteration and gets the last columnname i.e. from 'three'. If we need to create a single vector

vector2 <- c()
for(i in vector1) vector2 <- c(vector2, get(i)$columname)
Sign up to request clarification or add additional context in comments.

Comments

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.