我有如下数据集
name col1 col2
a 10.3 10.9
b 11 15
c 20 7.2
d 6.2 6.2
e 5.3 5.4
f 4.5 4.0
我想比较我的df的col1和col2,并且我要创建另一列,在其中比较col1和col2的值时,如果col2的值从col1开始增加,那么我想在那一列中输入旁边的增加值,如果它们是减少然后我要写减少并且如果它们相同则没有变化
我想要这样的输出
name col1 col2 col3
a 10.3 10.9 increasing
b 11 15 increasing
c 20 7.2 decreasing
d 6.2 6.2 no change
e 5.3 5.4 increasing
f 4.5 4.0 decreasing
与dplyr
:
df %>%
mutate(Col3=ifelse(col2 == col1,
"no change",
ifelse(col2 > col1,
"increasing","decreasing")))
或case_when
按照@akrun的建议使用:
df %>%
mutate(Col3 = case_when(col1 == col2 ~ "no change" ,
col2 > col1 ~ "Increasing",
TRUE ~ "decreasing"))
结果:
name col1 col2 Col3
1 a 10.3 10.9 increasing
2 b 11.0 15.0 increasing
3 c 20.0 7.2 decreasing
4 d 6.2 6.2 no change
5 e 5.3 5.4 increasing
6 f 4.5 4.0 decreasing
数据:
df<-structure(list(name = c("a", "b", "c", "d", "e", "f"), col1 = c(10.3,
11, 20, 6.2, 5.3, 4.5), col2 = c(10.9, 15, 7.2, 6.2, 5.4, 4)), class = "data.frame", row.names = c(NA,
-6L))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句