r - 如何将函数仅应用于 R 中数据框中的数字字段(不包括标题)

标签 r

我有一个数据框这个数据框:

    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")

我需要对所有数据点全局应用舍入函数,不包括标题和日期时间格式的数据点:

我试过这个:
sapply(df, function(x) round(df[,2:ncol(x)],2))

不工作,有什么想法吗?

最佳答案

由于那里有所有因子列,因此您可能需要手动确定要转换的列。这是一个我们可以用来将因子转换为其原始数值的函数。这使用了 help(factor) 的警告部分中描述的推荐方法。 .

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

接下来,我们可以将此函数应用于所需的列并同时对它们进行四舍五入。在这种情况下,我们要申请 f()到除第一列之外的每一列,所以我们使用索引 [-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

检查生成的列类:
sapply(df, class)
#     Time   Server1   Server2 
# "factor" "numeric" "numeric" 

关于r - 如何将函数仅应用于 R 中数据框中的数字字段(不包括标题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28078238/

相关文章:

r - xtable和knitr : How to center table on full page width?

r - 如何自动排除 Predict.randomForest 中看不见的新因子水平?

r - 抑制R输出

r - 如何检查矩阵或数据框中是否存在列?

r - 将变量作为参数传递给 plot_ly 函数

r - 根据模式过滤R中的文件名

r - 有没有更简单的用交替模式重命名列的版本?还是 tidyverse 方法?

regex - 在第一个空格处分割字符串

r - 删除包含非英语字符的文本

r - 将 RDS 文件从 github 导入 R Windows