2

I know the deparse+substitute trick to get the name from an object passed as argument to a function, but the same trick inside a loop does no work.

My code (just for testing):

mylist <- list(first = c("lawyer","janitor"), second = c("engineer","housewife"))

for (element in names(mylist)){
  print(deparse(substitute(mylist[[element]])))
}

[1] "mylist[[element]]"
[1] "mylist[[element]]"

is there any way of getting the result?:

first
second
2
  • 2
    In your example you can just use print(element).. Commented Feb 14, 2017 at 8:59
  • 1
    What's wrong with names(mylist) ? Commented Feb 14, 2017 at 8:59

2 Answers 2

2

using lapply

lapply(mylist, function(x) { print(names(x))} )
# NULL
# NULL
# $first
# NULL
# 
# $second
# NULL

using for loop as per your question

for (element in names(mylist)){
  print(element)
}
# [1] "first"
# [1] "second"
Sign up to request clarification or add additional context in comments.

1 Comment

The lapply is doing something slightly different, since it applies the names function to each list element, returning NULL because they don't have names in the example.
1

Use "names"

for (element in names(mylist)){
  print(as.name(element))
}

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.