Warm tip: This article is reproduced from stackoverflow.com, please click
dataframe r

Formatting individual variables in a dataframe

发布于 2020-03-31 22:58:23

I have a simple question. I have a large dataset with text and numerical variables. I would like to format the numerical variables, but without saving them in a separate dataset and re-merging them (that would take way to much time).

How do I do this?

Here is a minimal example of what I mean:

a <- c("name1", "name2", "name3")
b <- rnorm(3)

df <- data.frame(a=a, b=b)

df<- format(round(df, 3), nsmall=3) 

This gives me an error as "a" is a non-numeric variable. So how do I format just "b"?

Questioner
Stata_user
Viewed
31
zx8754 2020-01-31 19:52

Format one column:

df$b <- format(round(df$b, 3), nsmall = 3)

If we need to format many numeric columns:

ix <- sapply(df, is.numeric)
df[ ix ] <- format(round(df[ ix ], 3), nsmall = 3)