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

时间:2016-03-07 18:21:35

标签: r format character numeric

我正在为简单的ANOVA演示建立一个示例,如果没有我的数字向量转向“字符”向量,似乎无法设置小数长度,是否有解决方案?

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

1 个答案:

答案 0 :(得分:0)

如果你真的想扔掉这些信息,你可以进行回合:

ServiceStack.Redis.IRedisClient.GetValues<int?>

漂亮打印是一种文本格式问题。因此,解决方案为您提供了字符串:

head(round(mysteryOne[, 1], 2))
# [1] 19.99 26.39 30.39 20.31 21.32 23.22

格式化输出然后将其重新强制转换为数字几乎肯定不是您想要的。