1

I have a list of 2 vectors named X, Y. I want to add a new element called H to each of these 2 vectors which will show as H = TRUE or FALSE.

BUT, instead of showing TRUE or FALSE my output shows 1 and 0. How can I show TRUE and FALSE in my current output?

H = c(T, F) # The element to be added

L <- list(X = c(K = 22, M = 39), Y = c(K = 54, M = 65)) # List to add to

Map(c, L, H = H) # My current solution

# Current OUTPUT:
# $X
#  K     M     H 
#  22   39     1   # instead of `TRUE`

# $Y
#  K     M     H 
# 54    65     0  # instead of `FALSE`
rnorouzian
  • 7,397
  • 5
  • 27
  • 72
  • use `as.logical()` to get from 0/1 to FALSE/TRUE – morgan121 Oct 10 '19 at 04:36
  • 1
    what doesn't work about it? how did you write it? And maybe lists have some limitation that they all need to be the same type? I feel like I've read that somewhere... not sure though – morgan121 Oct 10 '19 at 04:38

2 Answers2

3

You have this problem because each element of the list is a vector, and a vector is a collection of elements of the same type. So it is impossible to get what you want using vectors, the booleans will always be converted to numeric as this is the types of the already existing vectors.

But you could use lists inside the list

L <- list(X = list(K = 22, M = 39), Y = list(K = 54, M = 65))
Map(c, L, H = H)
fmarm
  • 4,209
  • 1
  • 17
  • 29
1

We can also convert the vector to list with as.list from the initial data and concatenate (c) as vector doesn't allow multiple types

Map(c, lapply(L, as.list), H = H)
akrun
  • 874,273
  • 37
  • 540
  • 662