1

I am a beginner in R, so I am sorry if the question was asked here before, however I did not found something similar:

What I needed is just to return the length of a vector (I have two vectors of the length 5 and 6 in the environment) from a command, conjoint with ls:

 for (i in ls()) {print (length(noquote(i)))}  

However, for both vectors this returns 1.

Thanks for a prompt.

MirrG
  • 406
  • 3
  • 10
  • 1
    `for( i in ls() ) {print( length( get(i) ) )}` – Artem Sokolov Aug 21 '18 at 17:43
  • 1
    In this situation you want `print(length(get(i)))`. But rarely do you want to print everything in `ls()`. – Thomas Aug 21 '18 at 17:43
  • Could you please make your question [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? `dput` output of your vectors would be helpful. – OzanStats Aug 21 '18 at 17:43
  • `ls()` calls the names of all vectors / dataframes / etc. in your environment. Each name is only going to have a length of 1. So it did what you told it to! – Punintended Aug 21 '18 at 17:44

2 Answers2

1

ls() returns a vector of strings (of type character). You are looping through those strings, removing the quotes from them, and then asking how long these character objects are.

What you want to do is access the object with a given name. To do that, you pass the name of the object as a character to the function get. get will accept the name of an object, search for it in the environment, and return the actual object, if it exists. You can then pass that into length to get the length of the object:

for (i in ls()) {print (length(get(i)))}
divibisan
  • 11,659
  • 11
  • 40
  • 58
1

We can use sapply with mget to count the length of each object in your global environment. mget takes a character vector with the names of objects (in this case a vector of object names in your global environment returned by ls()), and returns a list of objects stored in each name. sapply then counts the length of each element of the list and return a vector of lengths:

sapply(mget(ls()), length)
acylam
  • 18,231
  • 5
  • 36
  • 45