[英]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,它基于 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
I've tried using a code like this data$B <- c(tail(data$A, -1), NA))
, but I'm getting incorrect number of decimals (eg values with 6 decimal points turn into 5 decimal points).我试过使用这样的代码
data$B <- c(tail(data$A, -1), NA))
,但我得到的小数位数不正确(例如,6个小数点的值变成5个小数点)。 I want B values to follow exactly the A values, which includes decimal points.我希望 B 值完全遵循 A 值,其中包括小数点。
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.这显示了我在实际数据集中遇到的问题,即当我使用 mutate() function 时 B 变圆,正如@akrun 建议的那样。
A B
1 7.933333 16.01667
2 16.016667 24.53333
3 24.533333 34.70000
4 34.700000 NA
We can use lead
with mutate
in dplyr
我们可以在
dplyr
中使用带mutate
的lead
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
基于OP的代码,让我们尝试一个
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.