Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you apply a fucntion to only numeric fields in data frame in R (excluding headers)

Tags:

r

I have a data frame this data frame:

    structure(list(Time = structure(1:3, .Label = c("1/13/15 12:14 PM", 
"1/13/15 13:14 PM", "1/13/15 14:14 PM"), class = "factor"), Server1 = structure(1:3, .Label = c("3", 
"5", "7"), class = "factor"), Server2 = structure(1:3, .Label = c("0", 
"1.3", "34"), class = "factor")), .Names = c("Time", "Server1", 
"Server2"), row.names = c(NA, -3L), class = "data.frame")

I need to globaly apply a rounding function to all data points, excluding headers and datetime formated data points:

I tried this:

sapply(df, function(x) round(df[,2:ncol(x)],2))

not working, any ideas?

like image 316
user1471980 Avatar asked Oct 30 '25 05:10

user1471980


1 Answers

Since you've got all factor columns there, you'll likely need to manually determine which ones are to be converted. Here's a function we can use to convert factors to their original numeric values. This uses the recommended method as described in the Warning section of help(factor).

f <- function(x) as.numeric(levels(x))[x]

Next we can apply this function to the desired columns and round them at the same time. In this case we want to apply f() to every column except the first, so we use the index [-1].

df[-1] <- lapply(df[-1], function(x) round(f(x), 2))
df
#               Time Server1 Server2
# 1 1/13/15 12:14 PM       3     0.0
# 2 1/13/15 13:14 PM       5     1.3
# 3 1/13/15 14:14 PM       7    34.0

Check the resulting column classes:

sapply(df, class)
#     Time   Server1   Server2 
# "factor" "numeric" "numeric" 
like image 122
Rich Scriven Avatar answered Nov 03 '25 01:11

Rich Scriven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!