Print rest of list in iteration with indeterminate length in same paste function

Viewed 10

I am new to R and need help with this iterable. Here is my code:

vec1 <- c("John", "Cat")
vec2 <- c("Matthew", "Dino", "Dog", "Bird")
vec3 <- c("James", "Snail", "Worm", "Frog", "Dragon")
list1<- list(vec1, vec2, vec3)

printer <- function(list1) {
  for (item in list1) {
    print(paste(paste(item[1], "'s pets are", sep = ''), paste(item[2:length(item)], sep = ' ')))
  }
}

printer(list1)

The result

[1] "John's pets are Cat"
[1] "Matthew's pets are Dino" "Matthew's pets are Dog"  "Matthew's pets are Bird"
[1] "James's pets are Snail"  "James's pets are Worm"   "James's pets are Frog"   "James's pets are Dragon"

I'm trying to have the pet names all print in the same line, but they keep printing separate.

1 Answers

In the second paste, it should be collapse instead of sep

for (item in list1) {
    print(paste(paste(item[1], "'s pets are", sep = ''), 
       paste(item[2:length(item)], collapse = ' ')))
  }

-output

[1] "John's pets are Cat"
[1] "Matthew's pets are Dino Dog Bird"
[1] "James's pets are Snail Worm Frog Dragon"

or use toString)

for(item in list1) print(paste0(item[1], "'s pets are ", toString(item[-1])))
Related