2016-03-07 189 views
0

我正在爲一個簡單的ANOVA演示構建一個示例,如果沒有將數字向量轉換爲「字符」向量,似乎無法設置小數長度,是否有解決方案?爲什麼format()將數字變量轉換爲字符變量?

# 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

只是格式__after__做所有計算。 –

+0

因爲'format'函數的作用就是這樣。請參閱幫助文件'?format'。如果要以更高的精度顯示浮點數,請更改您的選項:'pi;選項(數字= 20); pi'。 – nrussell

+0

謝謝,格式化後指定的類型是我現在要使用的默認方法。我想知道是否我可能不想使用format()命令。格式()幫助文件中的這個語句讓我認爲我錯過了一些東西:「數字向量編碼時所需的最小小數位數將所有元素顯示爲至少有效數字的位數。」 –

回答

0

您可以全面,如果你真的想扔掉的信息:

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

漂亮的印刷是一個文本格式的問題。因此,解決方案爲您提供的字符串:

head(format(mysteryOne[, 1], nsmall = 2L, digits = 2)) 
# [1] "19.99" "26.39" "30.39" "20.31" "21.32" "23.22" 

格式化輸出,然後強迫它到數字幾乎肯定不是你想要的。