仅舍入数字输入,否则在 R 中跳过
round only input that is numeric otherwise skip in R
我想知道是否有一种方法可以在 R 中自定义 round
,这样如果输入非数字(例如 "No"
),round
只会输出非数字但只是围绕另一个数字输入?
这是我尝试过但没有成功的方法:
a = c(.56789, "No", .87542) ## round numerics but just output the non-numeric
roundif <- function(x, digits) if(any(!is.numeric(x))) x else round(x, digits)
roundif(a, 2)
我们可以使用 grepl
创建一个逻辑索引来对数字元素进行子集化。在函数中,grepl
将检查元素中是否有任何字母([A-Za-z]
)。它可以进一步推广以包括其他字符(如果需要)
roundif <- function(x, digits) {
i1 <- grepl('[A-Za-z]', x) # logical index
x1 <- as.list(x) # convert to a list
x1[!i1] <- round(as.numeric(a[!i1]), digits) # assign rounded values
x1
}
roundif(a, 2)
#[[1]]
#[1] 0.57
#[[2]]
#[1] "No"
#[[3]]
#[1] 0.88
注意:vector
被转换为 list
,因为 vector
只能容纳一个 type
我想知道是否有一种方法可以在 R 中自定义 round
,这样如果输入非数字(例如 "No"
),round
只会输出非数字但只是围绕另一个数字输入?
这是我尝试过但没有成功的方法:
a = c(.56789, "No", .87542) ## round numerics but just output the non-numeric
roundif <- function(x, digits) if(any(!is.numeric(x))) x else round(x, digits)
roundif(a, 2)
我们可以使用 grepl
创建一个逻辑索引来对数字元素进行子集化。在函数中,grepl
将检查元素中是否有任何字母([A-Za-z]
)。它可以进一步推广以包括其他字符(如果需要)
roundif <- function(x, digits) {
i1 <- grepl('[A-Za-z]', x) # logical index
x1 <- as.list(x) # convert to a list
x1[!i1] <- round(as.numeric(a[!i1]), digits) # assign rounded values
x1
}
roundif(a, 2)
#[[1]]
#[1] 0.57
#[[2]]
#[1] "No"
#[[3]]
#[1] 0.88
注意:vector
被转换为 list
,因为 vector
只能容纳一个 type