[英]R mutate new column based on range of values in other column
I have r dataframe in following format我有以下格式的 r dataframe
+--------+---------------+--------------------+--------+
| time | Stress_ratio | shear_displacement | CX |
+--------+---------------+--------------------+--------+
| <dbl> | <dbl> | <dbl> | <dbl> |
| 50.1 | -0.224 | 4.9 | 0 |
| 50.2 | -0.219 | 4.98 | 0.0100 |
| . | . | . | . |
| . | . | . | . |
| 249.3 | -0.217 | 4.97 | 0.0200 |
| 250.4 | -0.214 | 4.96 | 0.0300 |
| 251.1 | -0.222 | 4.91 | 0.06 |
| 252.1 | -0.222 | 4.91 | 0.06 |
| 253.3 | -0.222 | 4.91 | 0.06 |
| 254.5 | -0.222 | 4.91 | 0.06 |
| 256.8 | -0.222 | 4.91 | 0.06 |
| . | . | . | . |
| . | . | . | . |
| 500.1 | -0.22 | 4.91 | 0.6 |
| 501.4 | -0.22 | 4.91 | 0.6 |
| 503.1 | -0.22 | 4.91 | 0.6 |
+--------+---------------+--------------------+--------+
and I want a new column which has repetitive values based on the difference between a range of values in column time.我想要一个新列,它具有基于列时间中一系列值之间的差异的重复值。 The range should be 250 for the column time.
列时间的范围应为 250。 For example in all the rows of
new_column
I should get number 1 when df$time[1]
and df$time[1]*4.98
is 250. Similarly this number 1 should change to 2 when the next chunk starts of difference of 250. So the new dataframe should be like例如,在
new_column
的所有行中,当df$time[1]
和df$time[1]*4.98
为 250 时,我应该得到数字 1。类似地,当下一个块开始时相差 250 时,这个数字 1 应该变为 2。所以新的 dataframe 应该是这样的
+--------+---------------+--------------------+--------+------------+
| time | Stress_ratio | shear_displacement | CX | new_column |
+--------+---------------+--------------------+--------+------------+
| <dbl> | <dbl> | <dbl> | <dbl> | <dbl> |
| 50.1 | -0.224 | 4.9 | 0 | 1 |
| 50.2 | -0.219 | 4.98 | 0.0100 | 1 |
| . | . | . | . | 1 |
| . | . | . | . | 1 |
| 249.3 | -0.217 | 4.97 | 0.0200 | 1 |
| 250.4 | -0.214 | 4.96 | 0.0300 | 2 |
| 251.1 | -0.222 | 4.91 | 0.06 | 2 |
| 252.1 | -0.222 | 4.91 | 0.06 | 2 |
| 253.3 | -0.222 | 4.91 | 0.06 | 2 |
| 254.5 | -0.222 | 4.91 | 0.06 | 2 |
| 256.8 | -0.222 | 4.91 | 0.06 | 2 |
| . | . | . | . | . |
| . | . | . | . | . |
| 499.1 | -0.22 | 4.91 | 0.6 | 2 |
| 501.4 | -0.22 | 4.91 | 0.6 | 3 |
| 503.1 | -0.22 | 4.91 | 0.6 | 3 |
+--------+---------------+--------------------+--------+------------+
If I understand what you're trying to do, a base
R solution could be:如果我明白你想做什么,一个
base
的 R 解决方案可能是:
df$new_column <- df$time %/% 250 + 1
The %/%
operator is integer division (sort of the complement of the modulus operator) and tells you how many copies of 250 would fit into your number; %/%
运算符是 integer 除法(模数运算符的补码)并告诉您 250 的副本有多少适合您的数字; we add 1 to get the value you want.我们加 1 以获得您想要的值。
The tidyverse
version: tidyverse
版本:
df <- df %>%
mutate(new_column = time %/% 250 + 1)
library(data.table)
setDT(df)[, new_column := rleid(time %/% 250)][]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.