gpt4 book ai didi

使用 ifelse 仅对数值变量进行舍入

转载 作者:行者123 更新时间:2023-12-02 19:24:02 27 4
gpt4 key购买 nike

我有一个非常大的数据框(大约 100 行,200 列)。我的数据子集如下所示:

example <- data.frame("Station" = c("012", "013", "014"), "Value1" = c(145.23453, 1.022342, 0.4432), 
"Value2" = c(2.1221213, 4445.2231412, 0.3333421), "Name" = c("ABC", "SDS", "EFG"))

我想用这些条件对表中的所有数值变量进行四舍五入。

如果 x<1,则 1 sig Fig

如果 1<= x < 99,则 2 个数字

如果 x>= 100,则 3 个数字

我知道对特定列执行类似的操作:

example$Value1 <- ifelse(example$Value1 < 1, signif(example$Value1, 1), example$Value1)

但我不确定如何处理混合有数字和字符值的大型数据框。

最佳答案

只需将ifelse放入lapply即可。要标识数字列,请在 sapply 中使用 negate is.character。您还可以矢量化一个小的替换FUN Action ,其中包含要在lapply中使用的所有所需条件,这可能会很方便。但是,请注意@GKi 的评论,您的条件并不完整。

nums <- sapply(example, is.numeric)

FUN <- Vectorize(function(x) {
if (x < 1) x <- signif(x, 1)
if (1 <= x & x < 99) x <- signif(x, 2)
if (x >= 100) x <- signif(x, 3)
x
})

example[nums] <- lapply(example[nums], FUN)
# Station Value1 Value2 Name
# 1 012 145.0 2.1 ABC
# 2 013 1.0 4450.0 SDS
# 3 014 0.4 0.3 EFG

关于使用 ifelse 仅对数值变量进行舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62636562/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com