应用如下逻辑:
常数= 5
如果count <=常数,则从值1开始打印行。一旦count>常数,则从值2开始打印行。
不使用索引-切片,需要逻辑,因为将来可以更改常量。
预期输出:
count value_1 value_2 output
1 0.001138636 0.081404856 0.001138636
2 0.001157974 0.089056417 0.001157974
3 0.00117294 0.098103887 0.00117294
4 0.00124517 0.109297111 0.00124517
5 0.001369958 0.123153932 0.001369958
6 0.001494746 0.141047465 0.141047465
7 0.001619535 0.165075631 0.165075631
8 0.001744323 0.198308568 0.198308568
9 0.001771541 0.248464171 0.248464171
10 0.001713549 0.331921807 0.331921807
答案 0 :(得分:1)
我们可以使用ifelse
df$output <- with(df, ifelse(count <= constant, value_1, value_2))
df$output
#[1] 0.001138636 0.001157974 0.001172940 0.001245170 0.001369958 0.141047465 0.165075631 0.198308568
#[9] 0.248464171 0.331921807
或与tidyverse
library(tidyverse)
df %>%
mutate(output = case_when(count <= constant ~ value_1,
TRUE ~ value_2))
df <- structure(list(count = 1:10, value_1 = c(0.001138636, 0.001157974,
0.00117294, 0.00124517, 0.001369958, 0.001494746, 0.001619535,
0.001744323, 0.001771541, 0.001713549), value_2 = c(0.081404856,
0.089056417, 0.098103887, 0.109297111, 0.123153932, 0.141047465,
0.165075631, 0.198308568, 0.248464171, 0.331921807)), row.names = c(NA,
-10L), class = "data.frame")
答案 1 :(得分:0)
使用data.table
可以尝试:
library(data.table)
setDT(df)[,output := ifelse(count <= 5, value_1,value_2)]
df
#returns
count value_1 value_2 output
1: 1 0.001138636 0.08140486 0.001138636
2: 2 0.001157974 0.08905642 0.001157974
3: 3 0.001172940 0.09810389 0.001172940
4: 4 0.001245170 0.10929711 0.001245170
5: 5 0.001369958 0.12315393 0.001369958
6: 6 0.001494746 0.14104747 0.141047465
7: 7 0.001619535 0.16507563 0.165075631
8: 8 0.001744323 0.19830857 0.198308568
9: 9 0.001771541 0.24846417 0.248464171
10: 10 0.001713549 0.33192181 0.331921807