简体   繁体   English

R 通过替换另一列中的值来更改 gt 表中有效数字的数量

[英]R change number of significant figures in a gt table by replacing values from another column

I am trying to create a series of gt tables with values shown to a 3rd sig fig.我正在尝试创建一系列 gt 表,其中的值显示到第三个 sig 图。 Because I want to show non numeric characters, the column I want to display is a factor.因为我想显示非数字字符,所以我想显示的列是一个因素。 What's the best way to do this?做到这一点的最佳方法是什么? I thought I could replace the values of a factor column with those from a numeric column, but I am not sure how to go about it.我以为我可以用数字列中的值替换因子列的值,但我不确定如何去做。 The code below is an example of a larger data set, where I would want to replace all numeric like values in Area1 with corresponding shorter values in Area2下面的代码是一个更大的数据集的例子,我想用 Area2 中相应的较短值替换 Area1 中的所有类似数值的值

Area1 <- as.factor(c(0,0, 0.50659782, "NS"))
Area2 <- c(NA, NA, 0.507, NA)
d <-data.frame(Area1, Area2) %>% gt() 

Essentially, I want to Area1 column to look like本质上,我想让 Area1 列看起来像

Area1
0
0
0.507
NS

Since your data has mixed types the numbers are already changed to characters/factors.由于您的数据具有混合类型,因此数字已更改为字符/因子。 You can use regex approach to keep data only till 3 decimal places.您可以使用正则表达式方法将数据保留到小数点后 3 位。

library(gt)
Area1 <- as.factor(c(0,0, 0.50659782, "NS"))
Area2 <- c(NA, NA, 0.507, NA)
d <-data.frame(Area1, Area2) 
d$Area1 <- ifelse(is.na(d$Area2), as.character(d$Area1), d$Area2)
d <- d[-2]
gt(d)

在此处输入图片说明

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

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