r - 用于选择与行号对应的特定数字中的值
问题描述
例如,我有一个如下的 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
解决方案
很多方法可以做到这一点。
将您的数据框视为:
df <- data.frame(col1 = 1:5)
- 您可以
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
shift
在data.table
library(data.table)
setDT(df)[, col2 := shift(col1, type = "lead")/col1]
- 在基础 R 中:
一个。head
和tail
:_
transform(df, col2 = c(tail(col1, -1)/head(col1, -1), NA))
湾。通过索引
transform(df, col2 = c(col1[-1]/col1[-nrow(df)], NA))
推荐阅读
- ios - 奇怪的构建错误:Facebook Swift SDK 未在空白项目中使用 Carthage 构建
- angular - PrimeNg overlayPanel 包装面板菜单
- mysql - MySQL 通过多个 id 获取每个 id 的一个条目
- postgresql - 在带有 Spring-boot 的 postgres 中使用整数数组
- android - 改造离线兑现返回空 response.body()
- python - Selenium 嵌套循环到下一页
- excel - 循环遍历范围内的单元格以查找手动设置为空白的单元格
- string - 如何从字符串中删除确切数量的中间字符?
- html - 嵌入存储在 github 中的图像
- python - Python:无法使用 PdfPages 将 matplotlib hist2d 图保存到文件