1

I have a table in R containing n values. I want to create a column B, which has the values of another column A, but moved them "up" 1 line:

Example:

A    B
_    _
1    2
2    3
3    n
n    n

I know that the first item of A will be deleted in column B and also I would like to duplicate the value n and move it to the last "empty" spot of B (which would otherwise be 0 because I moved all values "up")

Max
  • 397
  • 5
  • 15
  • 1
    With `dplyr`, `df %>% mutate(B = lead(df$A))`. Add `%>% tidyr::fill(B)` if you like, though `NA` seems more useful than `"n"`. – alistaire May 27 '16 at 18:21
  • 1
    @Max This is already answered here http://stackoverflow.com/questions/25995257/r-shift-values-in-single-column-of-dataframe-up –  May 27 '16 at 18:25

3 Answers3

2
dat <- data.frame(A = c(1, 2, 3, 4))
dat$B <- dat$A[c(2:length(dat$A), length(dat$A))]

Should work.

Japhir
  • 564
  • 3
  • 17
  • 1
    @lmo thanks, I misread it. Assumed he wanted the first value to jump over to the end. Updated answer. – Japhir May 27 '16 at 18:49
2
df1$B <- with(df1,c(tail(A,-1),tail(A,1)))

Sample data:

df1 <- data.frame(A = c(1, 2, 3, 0))

Output:

#> df1
#  A B
#1 1 2
#2 2 3
#3 3 0
#4 0 0
RHertel
  • 23,412
  • 5
  • 38
  • 64
1

You could simply replace the values with

table$B[1:n-1] <- table$A[2:n]
ZachTurn
  • 636
  • 1
  • 5
  • 14