1

Example Data:

a <- c("cat", "dog", "mouse")
b <- c("spoon", "fork", "knife")
c <- c("auto", "boot", "bike")

Generate Variables:

objects <-c(a,b,c)
strings <-c("a","b","c")

Give me the length of all strings:

> nchar(objects)
[1] 3 3 5 5 4 5 4 4 4

> nchar(strings)
[1] 1 1 1

What do i have to do to "strings" to give me the same result as "objects"?

The closest i have gotten so far:

> nchar(eval(parse(text=strings)))
[1] 4 4 4
> 

But where is the rest?

4
  • 1
    I believe you want: nchar(unlist(lapply(strings,function(s) eval(parse(text=s))))) Commented Dec 5, 2016 at 15:42
  • Thank you. I will test your answers in my function and check the correct one if i get the result i want. Commented Dec 5, 2016 at 16:03
  • In case, you need a for loop, here is one v1 <- vector(); for(j in strings){ v1 <- c(v1, nchar(get(j))) } > v1 Commented Dec 5, 2016 at 16:16
  • @aichao. if you reply to my post i can set your comment as the answer. Commented Dec 6, 2016 at 16:07

3 Answers 3

3

We can use mget to return the values of the objects in a list, unlist it to a vector and get the nchar

nchar(unlist(mget(strings), use.names=FALSE))
#[1] 3 3 5 5 4 5 4 4 4
Sign up to request clarification or add additional context in comments.

Comments

2

One option is using sapply over each element of strings, get the value of element and calculate the number of characters with nchar

c(sapply(strings, function(x) nchar(get(x))))
#[1] 3 3 5 5 4 5 4 4 4

Comments

1

The key is to loop over each element of strings and apply eval(parse(text=s)). Then unlist to a vector and call nchar:

nchar(unlist(lapply(strings,function(s) eval(parse(text=s)))))
##[1] 3 3 5 5 4 5 4 4 4

Hope this helps.

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.