-2

I have a question about cbinding recycled items. I simplified my problem into the following code.

I have two objects "a" and "b". "a" has 5 rows and "b" has 10 rows.

When I cbind them, I get a data.frame with 10 rows, and my column "a" recycles until it reaches 10 rows. My problem is, how do i recycle the values so it adds to the length(a). Thanks!

a <- c(4, 3, 5, 2, 8)
b <- c(1:10)

cbind(a,b)


   a  b
1  4  1
2  3  2
3  5  3
4  2  4
5  8  5
6  4  6
7  3  7
8  5  8
9  2  9
10 8 10

What I want to do: a[6] = a[5] + 4, a[7] = a[5] + 5, ... a[10] = a[5] + 8


   a  b
1  4  1
2  3  2
3  5  3
4  2  4
5  8  5
6  12  6
7  11  7
8  13  8
9  10  9
10 16 10
NoVice
  • 43
  • 5
  • 1
    Suppose your `a <- c(4, 3, 5, 2, 8)`, what will be the `after` dataset after `cbind`? – akrun Feb 28 '15 at 16:27
  • 2
    Please try to add more information, your question is not clear at all. How should your program determine the values that are not in a? – Verena Haunschmid Feb 28 '15 at 16:29
  • Please provide more examples or a clearer explanation. – codingEnthusiast Feb 28 '15 at 16:37
  • sorry for the confusion, I changed "a" to akrun's response – NoVice Feb 28 '15 at 16:41
  • maybe c(4,3,5,2,8,14,13,15,12,18) or c(4,3,5,2,8,9,8,10,7,13)instead of what you have added? It's still unlear to me, I'm sorry mate. – codingEnthusiast Feb 28 '15 at 16:52
  • 1
    @NoVice The expected output is not clear as naltipar suggested – akrun Feb 28 '15 at 16:55
  • 1
    @NoVice Your expected output may be `cbind(a=c(a,a+a[length(a)])[1:length(b)],b)`, but I didn't understand it correctly. For example, suppose `b <- 1:15` – akrun Feb 28 '15 at 17:02
  • I believe the OP meant c(4,3,5,2,8,9,8,10,7,13), otherwise the OP's question makes no sense. – codingEnthusiast Feb 28 '15 at 17:05
  • Judging from the question, I don't think you understand what "recycling" means. R does this internally. You can't control the values that are added via recycling unless you change the vector that is being recycled, and possibly changing the length of the vectors it being compared to – Rich Scriven Feb 28 '15 at 17:20

1 Answers1

1

Do you mean this? I have 5 items and I'm adding a[5] to the the next 5 items, 2*a[5] to the next 5 items and so on.

a <- c(4, 3, 5, 2, 8)
b <- c(1:11)
counter <-0:floor(length(b)-1)/length(a))
new.col <- rep(a[length(a)] * counter, each = length(a)) + a
length(new.col) <- length(b)
new.col
[1]  4  3  5  2  8 12 11 13 10 16

The first length(a) items stay intact, we add a[5] to the next length(a) items, 2*a[5] to the next length(a) items and so on...

codingEnthusiast
  • 3,800
  • 2
  • 25
  • 37