r - R 格式仅适用于整数,删除小数
问题描述
如何有条件地删除小数,如果number > 0
.
尝试使用格式功能,并且map_dbl
. 它显示错误。目的是从 1.00、10.00 中删除 .00。
kk= c(0.001,0.01,1.00,10.00)
number <-function(number){
if(number>0){
result <- format(number,nsmall = 0)
return(result)
}
}
map_dbl(kk,number)
实际:错误:无法将元素 1 从字符强制转换为双精度
预期:0.001,0.01,1,10
解决方案
假设您想要一个字符向量作为输出:
sapply(c(0.001, 0.01, 1, 10),
function(x) ifelse(x<1, x, round(x,0)))
[1] "0.001" "0.01" "1" "10"
要使用字符向量标记 ggplot 中的轴:
library(ggplot2)
axisLabels <- function(x) ifelse(x<1, x, as.character(round(x, 0)))
df <- data.frame(group=letters[1:5],
value=c(.023, .0473, 1.2, 1.5, 1.9))
ggplot(df, aes(x=group, y=value)) +
geom_bar(stat="identity") +
scale_y_continuous(breaks=seq(0, 2, .1),
labels=sapply(seq(0,2,.1), axisLabels))
推荐阅读
- php - 删除空的< >
- html - 灵活的菱形网格,图像已经是菱形
- gem5 - gem5的Simple.py配置中的Icache和Dcache
- python-3.x - 使用 Selenium (python) 问题在表单内选择下拉菜单选项
- react-native - 反应原生。过滤器 FlatList - 错误“索引 = 10 计数 0”
- android - 有没有办法在android中分支出重复的usb信息?
- reactjs - 如何在编辑后更新 react-bootstrap-table2 单元格值,以便不同列中的按钮组件具有它?
- rspec - 没有实际文件的模块中的 RSpec 测试类
- javascript - 如何删除这些 D3.js 控制台日志错误
- java - 我可以用什么来屏蔽字符串?