0

I have many numerical scalars/vectors, like:

a <- 1
b <- c(2,4)
c <- c(5,6,7)
d <- c(60, 556, 30, 4, 5556, 111232)

Now I need to add to every number in scalar/vector 1 and insert the result after that number. The solution should work with any numerical scalars and vectors. So result should look like:

a <- c(1,2)
b <- c(2,3,4,5)
c <- c(5,6,6,7,7,8)
d <- c(60, 61, 556, 557, 30, 31, 4, 5, 5556, 5557, 111232, 111233)

How this can be done?

vasili111
  • 6,032
  • 10
  • 50
  • 80

1 Answers1

2
lst <- list(
  a = 1,
  b = c(2,4),
  c = c(5,6,7),
  d = c(60, 556, 30, 4, 5556, 111232))

lapply(lst, function(x) as.vector(rbind(x, x + 1)))
# $`a`
# [1] 1 2
# 
# $b
# [1] 2 3 4 5
# 
# $c
# [1] 5 6 6 7 7 8
# 
# $d
#  [1]     60     61    556    557     30     31      4      5   5556   5557 111232 111233

This is pretty much a dupe of this, but not exactly so I'll let someone else make the call.

IceCreamToucan
  • 28,083
  • 2
  • 22
  • 38
  • I tried to modified your code in order to process one scalar/vector at one time and get result as vector (that I need): `b = c(2,4)` `apply(b, function(x) rbind(x, x + 1))` . But that gives me error. How can I modify it to work? – vasili111 Dec 05 '19 at 19:06
  • You can run as `as.vector(rbind(b, b + 1))` – IceCreamToucan Dec 05 '19 at 19:07
  • This `b = c(2,4)` `apply(b, function(x) as.vector(rbind(b, b + 1)))` gives me error : `Error in match.fun(FUN) : argument "FUN" is missing, with no default` – vasili111 Dec 05 '19 at 19:10
  • Same with `b = c(2,4)` ` apply(b, function(b) as.vector(rbind(b, b + 1)))` – vasili111 Dec 05 '19 at 19:11
  • 1
    Just `as.vector(rbind(b, b + 1))`. It is already vectorized, no need for apply. – IceCreamToucan Dec 05 '19 at 19:11
  • 1
    Or an option with tidyverse `enframe(lst) %>% group_by(name) %>% summarise(value = list(c(rbind(value[[1]], value[[1]] +1)))) %>% deframe` – akrun Dec 05 '19 at 20:00