首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么format()将数值变量转换为字符变量?

为什么format()将数值变量转换为字符变量?
EN

Stack Overflow用户
提问于 2016-03-08 02:21:35
回答 1查看 51关注 0票数 0

我正在为一个简单的方差分析演示构建一个示例,如果不将数字向量转换为“字符”向量,似乎无法设置小数长度,有解决方案吗?

代码语言:javascript
复制
# use fGarch for building somewhat messy data
library(fGarch)
N = 30
set.seed(1976)
control = rsnorm(N, 25, 5, 1.8)
treatOne = rnorm(N, 25, 4)
treatTwo = rsnorm(N, 22, 5, -1.3)
treatThree = rsnorm(N, 20, 5, -1)

# bind groups into a single dataframe
mysteryOne = data.frame(control, treatOne, treatTwo, treatThree)
# "stack" the dataframe to combine it into one column
mysteryOne = stack(mysteryOne)
# rename the columns
library(plyr)
mysteryOne = rename(mysteryOne, c("values" = "anxiety", "ind" = "condition"))
# replace the experimental "condition" values with a "group code" 
mysteryOne$condition = c(rep(0, N), rep(1, N), rep(2, N), rep(3, N))

# specify vector types
mysteryOne[, 1] = as.numeric(mysteryOne[, 1])
mysteryOne[, 2] = as.factor(mysteryOne[, 2])

# restrict the numeric vector to two decimal points
mysteryOne[, 1] = format(round(mysteryOne[, 1], 2), nsmall = 2)

str(mysteryOne)
EN

回答 1

Stack Overflow用户

发布于 2016-03-08 03:02:38

如果你真的想扔掉这些信息,你可以转一转:

代码语言:javascript
复制
head(round(mysteryOne[, 1], 2))
# [1] 19.99 26.39 30.39 20.31 21.32 23.22

美观的打印是一个文本格式问题。所以解决方案会给你字符串:

代码语言:javascript
复制
head(format(mysteryOne[, 1], nsmall = 2L, digits = 2))
# [1] "19.99" "26.39" "30.39" "20.31" "21.32" "23.22"

格式化输出,然后将其强制返回到数字,这几乎肯定不是您想要的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35851042

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档