2

I have the following list of vectors


v1 <-  c("foo","bar")
v2 <-  c("qux","uip","lsi")

mylist <- list(v1,v2)

mylist
#> [[1]]
#> [1] "foo" "bar"
#> 
#> [[2]]
#> [1] "qux" "uip" "lsi"

What I want to do is to apply a function so that it prints the this string:

v1:foo,bar
v2:qux,uip,lsi

So it involves two step: 1) Convert object variable to string and 2) make the vector into string. The latter is easy as I can do this:

make_string <- function (content_vector) {
  cat(content_vector,sep=",") 
}

make_string(mylist[[1]])
# foo,bar
make_string(mylist[[2]])
# qux,uip,lsi

I am aware of this solution, but I don't know how can I turn the object name into a string within a function so that it prints like my desired output.

I need to to this inside a function, because there are many other output I need to process.

pdubois
  • 7,640
  • 21
  • 70
  • 99

2 Answers2

3

We can use

cat(paste(c('v1', 'v2'), sapply(mylist, toString), sep=":", collapse="\n"), '\n')
#v1:foo, bar
#v2:qux, uip, lsi 

If we need to pass the original object i.e. 'v1', 'v2'

make_string <- function(vec){
    obj <- deparse(substitute(vec))

    paste(obj, toString(vec), sep=":")
} 

make_string(v1)
#[1] "v1:foo, bar"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • in your method `v1` and `v2` is hard coded as string. But I need to convert from object to string. – pdubois Jul 26 '17 at 07:48
  • 1
    @pdubois DId you meant to assign it to two vector objects – akrun Jul 26 '17 at 07:51
  • I mean I need `v1, v2` to be passed as object not string. See my update. – pdubois Jul 26 '17 at 07:52
  • Great. Thanks a million. Last question. How can I use purrr to apply `make_string` for all object in `mylist`? – pdubois Jul 26 '17 at 08:05
  • @pdubois But, in that case, there should be some indication of `v1', `v2`, as of now, there is nothing in mylist that relates to the original objects – akrun Jul 26 '17 at 08:07
1

If you want to use a list, you can name the objects in the list to be able to use them in a function. Remove the cat if you just want a string to be returned.

v1 <-  c("foo","bar")
v2 <-  c("qux","uip","lsi")

# objects given names here
mylist <- list("v1" = v1, "v2" = v2)

# see names now next to the $
mylist
$v1
[1] "foo" "bar"

$v2
[1] "qux" "uip" "lsi"

make_string <- function (content_vector) {
    vecname <- names(content_vector)
    cat(paste0(vecname, ":", paste(sapply(content_vector, toString), sep = ",")))
}

make_string(mylist[1])
v1:foo, bar

make_string(mylist[2])
v2:qux, uip, lsi
meenaparam
  • 1,949
  • 2
  • 17
  • 29