我正在处理一个来自swirl,r Programming Environment 12 Data Manipulation的问题。我想不出如何让r给我小数点后的正确位数。
我的代码:
titanic_4 <- titanic %>%
select(Survived, Pclass, Age, Sex) %>%
filter(!is.na(Age)) %>%
mutate(agecat = cut(Age, breaks = c(0, 14.99, 50, 150),
include.lowest = TRUE,
labels = c("Under 15", "15 to 50",
"Over 50"))) %>%
group_by(Pclass,agecat,Sex) %>%
summarize(N=n(), survivors = sum(Survived))%>%
mutate(perc_survived = (survivors/N)*100.000000)
head(titanic_4)提供:
# A tibble: 6 x 6
# Groups: Pclass, agecat [3]
Pclass agecat Sex N survivors perc_survived
<int> <fctr> <chr> <int> <int> <dbl>
1 1 Under 15 female 2 1 50.00000
2 1 Under 15 male 3 3 100.00000
3 1 15 to 50 female 70 68 97.14286
4 1 15 to 50 male 72 32 44.44444
5 1 Over 50 female 13 13 100.00000
6 1 Over 50 male 26 5 19.23077但是,我希望R在perc_survived中给我六位小数,这样它看起来就像这样:
## Pclass agecat Sex N survivors perc_survived
## <int> <fctr> <chr> <int> <int> <dbl>
## 1 Under 15 female 2 1 50.000000
## 1 Under 15 male 3 3 100.000000
## 1 15 to 50 female 70 68 97.142857
## 1 15 to 50 male 72 32 44.444444
## 1 Over 50 female 13 13 100.000000
## 1 Over 50 male 26 5 19.230769谁能告诉我怎么让r保留小数点后6位?
我尝试过sprintf:
> titanic_4 <- titanic %>%
+ select(Survived, Pclass, Age, Sex) %>%
+ filter(!is.na(Age)) %>%
+ mutate(agecat = cut(Age, breaks = c(0, 14.99, 50, 150),
+ include.lowest = TRUE,
+ labels = c("Under 15", "15 to 50",
+ "Over 50"))) %>%
+ group_by(Pclass,agecat,Sex) %>%
+ summarize(N=n(), survivors = sum(Survived))%>%
+ mutate(perc_survived = sprintf("%.6f",((survivors/N)*100.000000)))
>
> head(titanic_4)这就给出了:
# A tibble: 6 x 6
# Groups: Pclass, agecat [3]
Pclass agecat Sex N survivors perc_survived
<int> <fctr> <chr> <int> <int> <chr>
1 1 Under 15 female 2 1 50.000000
2 1 Under 15 male 3 3 100.000000
3 1 15 to 50 female 70 68 97.142857
4 1 15 to 50 male 72 32 44.444444
5 1 Over 50 female 13 13 100.000000
6 1 Over 50 male 26 5 19.230769添加sprintf纠正了小数位的问题,但也带来了新的问题。<chr>将列类型从sprintf更改为sprintf。
Swirl不会接受这个答案。有谁知道另一种方法吗?
非常感谢!
发布于 2018-01-19 22:03:53
您可以使用
> sprintf("%.6f", .1)
[1] "0.100000"发布于 2018-01-26 00:39:08
sprintf是一个字符串操作函数,因此根据定义它将返回一个字符串。如果您只是简单地尝试四舍五入到一组数字,则round或signif (有效数字)都应该有效。两者都有要保留的位数的参数。所以看起来mutate(perc_survived = round((survivors / N) * 100, digits = 6))会给你想要的东西。如果您想要有效数字的数量,而不是简单的四舍五入,请使用signif。
https://stackoverflow.com/questions/48341878
复制相似问题