简体   繁体   English

tidyr :: unite丢弃小数0

[英]tidyr::unite drops decimal 0

I want to combine numbers from two and two columns within a data frame (values in the columns are the upper and lower values for confidence intervals in statistical analysis). 我想合并数据帧中两列和两列中的数字(列中的值是统计分析中置信区间的上限值和下限值)。

My perferred method would be to use tidyr and the unite function. 我认为最好的方法是使用tidyrunite函数。 But take 0.20 as an example, that number will be modified to 0.2, ie these last decimals in numbers are dropped if they are equal to zero. 但是以0.20为例,该数字将修改为0.2,即如果这些数字等于零,则将删除这些数字的最后十进制。 Is there any way to keep the original format when using unite ? 使用unite时,有什么方法可以保留原始格式吗?

unite is describe here: https://www.rdocumentation.org/packages/tidyr/versions/0.8.2/topics/unite 此处描述了unitehttps//www.rdocumentation.org/packages/tidyr/versions/0.8.2/topics/unite

Example: 例:

# Dataframe
df <-  structure(list(est = c(0.05, -0.16, -0.02, 0, -0.11, 0.15, -0.26, 
-0.23), low2.5 = c(0.01, -0.2, -0.05, -0.03, -0.2, 0.1, -0.3, 
-0.28), up2.5 = c(0.09, -0.12, 0, 0.04, -0.01, 0.2, -0.22, -0.17
)), row.names = c(NA, 8L), class = "data.frame")

Combining (uniting) columns for confidence with unite , using a comma as a separator 使用逗号作为分隔符,将合并的列与unite相结合(合并)

library(tidyr)
df <- unite(df, "CI", c("low2.5", "up2.5"), sep = ", ", remove=T)

gives

df
    est           CI
1  0.05   0.01, 0.09
2 -0.16  -0.2, -0.12
3 -0.02     -0.05, 0
4  0.00  -0.03, 0.04
5 -0.11  -0.2, -0.01
6  0.15     0.1, 0.2
7 -0.26  -0.3, -0.22
8 -0.23 -0.28, -0.17

I would want this: 我想要这个:

    est           CI
1  0.05   0.01, 0.09
2 -0.16  -0.20, -0.12
3 -0.02  -0.05, 0.00
4  0.00  -0.03, 0.04
5 -0.11  -0.20, -0.01
6  0.15   0.10, 0.20
7 -0.26  -0.30, -0.22
8 -0.23  -0.28, -0.17

I believing doing this with Base R will be complicated (having to move/rearrange the many combined columns and delete the old columns). 我相信使用Base R这样做会很复杂(必须移动/重新排列许多合并的列并删除旧列)。 Is there any way to avoid unite from dropping decimals with the value of zero? 有什么方法可以避免unite丢弃零值的小数?

This works: 这有效:

library(tidyverse)

df %>% 
  mutate_if(is.numeric, ~format(., nsmall = 2)) %>% 
  unite("CI", c("low2.5", "up2.5"), sep = ", ", remove=T)
#    est           CI
#1  0.05  0.01,  0.09
#2 -0.16 -0.20, -0.12
#3 -0.02 -0.05,  0.00
#4  0.00 -0.03,  0.04
#5 -0.11 -0.20, -0.01
#6  0.15  0.10,  0.20
#7 -0.26 -0.30, -0.22
#8 -0.23 -0.28, -0.17

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM