首页 > 解决方案 > 用于选择与行号对应的特定数字中的值

问题描述

例如,我有一个如下的 df,我想计算 col 2 的任何行的值 = col1 的行 +1 的值 / col 1 的该行的值。插图如下。

如何编码上述想法并一直这样做到最后。请帮助。

Col1   Col2 
1      Value at row 2 of col1/ value at row 1 of col1?
2      Value at row 3 of col1/ value at row 2 of col1?
3   
4
5

标签: rdataframe

解决方案


很多方法可以做到这一点。

将您的数据框视为:

df <- data.frame(col1 = 1:5)
  1. 您可以lead使用dplyr
library(dplyr)
df %>% mutate(col2 = lead(col1)/col1)

#  col1 col2
#1    1 2.00
#2    2 1.50
#3    3 1.33
#4    4 1.25
#5    5   NA
  1. shiftdata.table
library(data.table)
setDT(df)[, col2 := shift(col1, type = "lead")/col1]
  1. 在基础 R 中:

一个。headtail:_

transform(df, col2 = c(tail(col1, -1)/head(col1, -1), NA))

湾。通过索引

transform(df, col2 = c(col1[-1]/col1[-nrow(df)], NA))

推荐阅读