我有如下数据集 名称col1 col2 一个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开始增加,那么我想在那一列中输入旁边的增加值,如果它们是减少然后我要写减少并且如果它们相同则保持不变 我想要这样的输出 名称col1 col2 col3 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减小
2021-01-31 08:13:52
使用dplyr: df%>% mutate(Col3 = ifelse(col2 == col1, “没有变化”, ifelse(col2> col1, “增加”,“减少”))) 或使用@akrun建议的case_when: df%>% mutate(Col3 = case_when(col1 == col2〜“ no change”, col2> col1〜“增加”, TRUE〜“减少”)) 结果: 名称col1 col2 Col3 1增加10.3 10.9 2 b 11.0 15.0增长 3 c 20.0 7.2减少 4 d 6.2 6.2不变 5 e 5.3 5.4增加 6 f 4.5 4.0减少 数据: 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)) | 我们可以用col2减去col1,然后使用符号分配值 df $ col3 <-c(“减少”,“无变化”,“增加”)[sign(df $ col1-df $ col2)+ 2] df #名称col1 col2 col3 #1 10.3 10.9减少 #2 b 11.0 15.0减少 #3 c 20.0 7.2增加 #4 d 6.2 6.2不变 #5 e 5.3 5.4降低 #6 f 4.5 4.0递增 或者使用dplyr我们可以使用case_when 图书馆(dplyr) df%>% mutate(col3 = case_when(col1 == col2〜“ no change”, col1> col2〜“增加”, TRUE〜“减少”)) | 基数R df $ col3 <-with(df,ifelse(col1> col2,“减少”, ifelse(col1