Drew
Drew

Reputation: 593

Creating a new column by using another column values

I have a dataset that looks like this:

data <- data.frame(A = c(3.132324,12.3439085,3.34343,5.1239048,6.34323,3.342334,9.342343,134.132433,13.1234323,23.34323))

Now, I want to use the A values to create a new column B that's based on the value one row below A. Like this:

      A          B
1    3.132324  12.343908
2   12.343908   3.343430
3    3.343430   5.123905
4    5.123905   6.343230
5    6.343230   3.342334
6    3.342334   9.342343
7    9.342343 134.132433
8  134.132433  13.123432
9   13.123432  23.343230
10  23.343230         NA

I've tried using a code like this data$B <- c(tail(data$A, -1), NA)), but I'm getting incorrect number of decimals (e.g. values with 6 decimal points turn into 5 decimal points). I want B values to follow exactly the A values, which includes decimal points.

How do I do this?

Update

This shows the problem I have in my actual dataset whereby the B becomes rounded when I use the mutate() function as @akrun suggests below.

     A        B
1  7.933333 16.01667
2 16.016667 24.53333
3 24.533333 34.70000
4 34.700000       NA  

Upvotes: 1

Views: 65

Answers (1)

akrun
akrun

Reputation: 887421

We can use lead with mutate in dplyr

library(dplyr)
data %>% 
     mutate(B = lead(A))
#           A          B
#1    3.132324  12.343908
#2   12.343908   3.343430
#3    3.343430   5.123905
#4    5.123905   6.343230
#5    6.343230   3.342334
#6    3.342334   9.342343
#7    9.342343 134.132433
#8  134.132433  13.123432
#9   13.123432  23.343230
#10  23.343230         NA

Based on the OP's code, let's try on a list

slotfinal <- list(data, data)
for(i in seq_along(slotfinal)) slotfinal[[i]] <- slotfinal[[i]] %>%
             mutate(B = lead(A))

slotfinal
#[[1]]
#            A          B
#1    3.132324  12.343908
#2   12.343908   3.343430
#3    3.343430   5.123905
#4    5.123905   6.343230
#5    6.343230   3.342334
#6    3.342334   9.342343
#7    9.342343 134.132433
#8  134.132433  13.123432
#9   13.123432  23.343230
#10  23.343230         NA

#[[2]]
#            A          B
#1    3.132324  12.343908
#2   12.343908   3.343430
#3    3.343430   5.123905
#4    5.123905   6.343230
#5    6.343230   3.342334
#6    3.342334   9.342343
#7    9.342343 134.132433
#8  134.132433  13.123432
#9   13.123432  23.343230
#10  23.343230         NA

Upvotes: 1

Related Questions