round all columns in R dataframe to 3 digits

To round all columns in an R dataframe to 3 digits, you can use the round() function along with the apply() function. Here are the steps to achieve this:

Step 1: Load the necessary libraries (if they are not already loaded). In this case, we'll need the dplyr library.

Step 2: Create a dataframe or load an existing dataframe into R.

Step 3: Use the apply() function to apply the round() function to each column of the dataframe. Set the MARGIN argument to 2 to indicate that the function should be applied to each column. Specify the number of digits to round to using the digits argument of the round() function.

Step 4: Assign the result back to the original dataframe or a new dataframe, depending on your requirements.

Here is an example code snippet that demonstrates these steps:

# Step 1: Load the necessary libraries
library(dplyr)

# Step 2: Create or load a dataframe
df <- data.frame(
  col1 = c(1.23456, 2.34567, 3.45678),
  col2 = c(4.56789, 5.67890, 6.78901)
)

# Step 3: Round each column to 3 digits
df <- apply(df, 2, function(x) round(x, digits = 3))

# Step 4: Assign the result back to the dataframe
df

This code will round each column in the dataframe df to 3 digits. The resulting dataframe will contain the rounded values.