Dplyrを使用して特定の列の値を丸める方法


R のdplyrパッケージを使用して、次のメソッドを使用してデータ フレームの特定の列の値を丸めることができます。

方法 1: 特定の列の値を丸める

 library (dplyr)

#round values in 'sales' and 'returns' columns to 2 decimal places 
df_new <- df %>% mutate(across(c(' sales ', ' returns '), round, 2 ))

方法 2: すべての数値列の値を四捨五入する

 library (dplyr)

#round values in all numeric columns to 2 decimal places
df_new <- df %>% mutate(across(where(is. numeric ), round, 2 ))

次の例は、R の次のデータ フレームで各メソッドを実際に使用する方法を示しています。

 #create data frame
df <- data. frame (store=c('A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'),
                 sales=c(4.352, 6.5543, 7.5423, 9.22111, 4.332, 9.55, 8.0094, 7.2),
                 returns=c(1.2324, 2.6654, 3.442, 6.545, 8.11, 8.004, 7.545, 6.0),
                 promos=c(12.11, 14.455, 10.277, 23.51, 20.099, 29.343, 30.1, 45.6))

#view data frame
df

  store sales returns promos
1 A 4.35200 1.2324 12.110
2 A 6.55430 2.6654 14.455
3 A 7.54230 3.4420 10.277
4 B 9.22111 6.5450 23.510
5 B 4.33200 8.1100 20.099
6 C 9.55000 8.0040 29.343
7 C 8.00940 7.5450 30.100
8 C 7.20000 6.0000 45.600

例 1: dplyr を使用して特定の列の値を丸める

次のコードは、 Sales 列Returns列の値を小数点第 2 位に四捨五入する方法を示しています。

 library (dplyr)

#round values in 'sales' and 'returns' columns to 2 decimal places 
df_new <- df %>% mutate(across(c(' sales ', ' returns '), round, 2 ))

#view updated data frame
df_new

  store sales returns promos
1 A 4.35 1.23 12.110
2 A 6.55 2.67 14.455
3 A 7.54 3.44 10.277
4 B 9.22 6.54 23.510
5 B 4.33 8.11 20.099
6C 9.55 8.00 29.343
7 C 8.01 7.54 30.100
8 C 7.20 6.00 45,600

Sales列とReturns列の値は小数点第 2 位に四捨五入されますが、他のすべての列は変更されないことに注意してください。

例 2: dplyr を使用してすべての数値列の値を丸める

次のコードは、すべての数値列の値を小数点第 2 位に四捨五入する方法を示しています。

 library (dplyr)

#round values in all numeric columns 2 decimal places 
df_new <- df %>% mutate(across(where(is. numeric ), round, 2 ))

#view updated data frame
df_new

  store sales returns promos
1 A 4.35 1.23 12.11
2 A 6.55 2.67 14.46
3 A 7.54 3.44 10.28
4 B 9.22 6.54 23.51
5 B 4.33 8.11 20.10
6C 9.55 8.00 29.34
7 C 8.01 7.54 30.10
8 C 7.20 6.00 45.60

データ フレーム内の 3 つの数値列の値は小数点第 2 位に四捨五入されていることに注意してください。

関連: dplyr で across() 関数を使用する方法

追加リソース

次のチュートリアルでは、dplyr で他の一般的なタスクを実行する方法を説明します。

dplyr: 列に文字列が含まれている場合に変数を変更する方法
dplyr: mutate() を使用して因子レベルを変更する方法
dplyr: 複数の列を追加する方法

コメントを追加する

メールアドレスが公開されることはありません。 が付いている欄は必須項目です