0

I am trying to use the for loop variables for an assingment in R. Let's say I have a list of 3 strings:

fruits = list('apple', 'pear', 'grape')

I wish to use these names to assign in a for loop e.g.

values = list()
for (name in fruits){
    values <- c(values, name = 5)
}

I would want a new list that looks like this:

values
apple = 5
pear = 5
grape = 5

However what I receieve is this:

values
name = 5
name = 5
name = 5

Is this possible in R or can this not be done?

Thanks

2
  • 1
    what are apple, pear and grape? Are they dataframes? Commented Aug 13, 2020 at 12:53
  • Apologies, they are strings Commented Aug 13, 2020 at 12:54

2 Answers 2

1

You can assign it with [[]]:

fruits = list("apple"," pear", "grape")

#I wish to use these names to assign in a for loop e.g.

values = list()
for (name in fruits){
    values[[name]] <- c(5)
}
Sign up to request clarification or add additional context in comments.

Comments

0

Also some times its easier not to set the names during a loop, but to set the names afterward. So if you have you list already

values <- list(5, 5, 5)
# or values <- as.list(rep(5,3))

you could do

values <- setNames(values, fruits)

Or if you are using Map() to get a value for each of these inputs, the result will be named for you assuming you pass in a character vector rather than a list. (And if you are just storing names, then a vector is probably better for most things)

Map(function(...) 5, as.character(fruits))
# $apple
# [1] 5
# $pear
# [1] 5
# $grape
# [1] 5

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.