我一直试图在具有多个值的数据框中对数字进行舍入,但无法找到方法。试图设置options(digits = 6)
,this主题中提供的解决方案以及其他一些解决方案。我的数据框架如下:
structure(list(X__1 = c("Start", "End", "EFM", "UTH", "PEU",
"HPX"), `TecM` = c("Mar-00", "Mar-01", "NA", "NA",
"-9.6432560109885879E-2", "-0.26834090581750103"), `TerA` = c("Sep-01",
"Sep-01", "NA", "NA", "0", "-0.11600490599886504"), `GloC` = c("Nov-07",
"Mar-09", "-0.62921737727223548", "NA", "-0.54549924666990268",
"-0.54518556256613238"), `ECis` = c("Jul-11",
"Sep-11", "-0.2912541254125412", "NA", "-0.21781440969547586",
"-0.18769305803934319"), `OSe` = c("Jul-14", "Dec-14",
"-0.10996326905417812", "-3.4236420002695674E-2", "-2.8281230134625412E-2",
"4.8566639665387892E-2")), .Names = c("X__1", "TecM",
"TerA", "GloC", "ECis",
"Oil Selloff"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-6L))
有没有简单的选择?
答案 0 :(得分:2)
我想还有一个tibble
解决方案,但我总是对在tibbles
中选择列等感到困惑。这就是我将其改为data.frame
。
jnk1 <- as.data.frame(jnk)
numeric_values <- !is.na(apply(jnk1, 2, as.numeric))
jnk1[numeric_values] <- round(as.numeric(jnk1[numeric_values]),1)
想象一下,您的数据称为ink
。将其另存为data.frame
。检查哪些值可以解析为数字,然后用圆值覆盖它们。
由于可能有警告,你可以用这一行来压制它们
numeric_values <- suppressWarnings(!is.na(apply(jnk1, 2, as.numeric)))
答案 1 :(得分:1)
如果只是为了更轻松地查看,以下行会将表格中所有看起来数字的值四舍五入为:
# assume df is your original data frame
suppressWarnings(data.frame(lapply(df, function(y) ifelse(is.na(as.numeric(y)), y, round(as.numeric(y), 2)))))
# result
X__1 TecM TerA GloC ECis Oil.Selloff
1 Start Mar-00 Sep-01 Nov-07 Jul-11 Jul-14
2 End Mar-01 Sep-01 Mar-09 Sep-11 Dec-14
3 EFM NA NA -0.63 -0.29 -0.11
4 UTH NA NA NA NA -0.03
5 PEU -0.1 0 -0.55 -0.22 -0.03
6 HPX -0.27 -0.12 -0.55 -0.19 0.05
但是数据框中带有数字/字符串/日期的列仍然是一列字符。