以下のようなデータセットがあります 名前col1col2 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から増加している場合は、列の横に増加を入力したいと思います。減少してから、減少して書きたいのですが、同じであれば変更はありません そして私はこのような私の出力が欲しい 名前col1col2 col3 10.310.9増加 b 1115増加 c 207.2減少 d 6.26.2変更なし e 5.35.4増加 f 4.54.0減少
2021-01-31 08:14:47
dplyrの場合: df%>% mutate(Col3 = ifelse(col2 == col1、 "変化なし"、 ifelse(col2> col1、 「増加する」、「減少する」))) または、@ akrunが提案するようにcase_whenを使用します: df%>% mutate(Col3 = case_when(col1 == col2〜 "変更なし"、 col2> col1〜 "増加"、 TRUE〜「減少」)) 結果: 名前col1col2 Col3 1 a 10.310.9増加 2 b 11.015.0増加 3 c 20.07.2減少 4 d 6.26.2変更なし 5 e 5.35.4増加 6 f 4.54.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)) | col1をcol2で減算し、符号を使用して値を割り当てることができます df $ col3 <-c( "減少"、 "変更なし"、 "増加")[sign(df $ col1-df $ col2)+ 2] df #名前col1 col2 col3 #1 a 10.310.9減少 #2 b 11.015.0減少 #3 c 20.07.2増加 #4 d 6.26.2変更なし #5 e 5.35.4減少 #6 f 4.54.0増加 または、dplyrを使用してcase_whenを使用できます ライブラリ(dplyr) df%>% mutate(col3 = case_when(col1 == col2〜 "変更なし"、 col1> col2〜 "増加"、 TRUE〜 "減少")) | ベースR df $ col3 <-with(df、ifelse(col1> col2、 "減少"、 ifelse(col1