![](/img/trans.png)
[英]the condition has length > 1 and only the first element will be used - in R
[英]condition has length > 1 and only the first element r
我有
df = data.frame(Col1 = c( NA, 1," ", 2345.768,"hi","", NA, 3.4, "44.99"))
并想要格式化特定值,并创建了一个 udf
format_it = function(y, n_decimals, dash_type, suffix = ""){
if(is.na(y)) return(dash_type)
if(nchar(gsub(" ", "", y))==0) return(y)
has_letter = grep("[A-z]+", y)
if(is_empty(has_letter)== TRUE) {
return(paste0(format(round(as.numeric(y), n_decimals), nsmall=n_decimals, big.mark = ","),suffix))
}
if(has_letter == 1){
return(y)
} else{
x = as.numeric(y)
ifelse(is.na(x),
dash_type,
paste0(format(round(as.numeric(x), n_decimals), nsmall=n_decimals, big.mark = ","),suffix))}
}
我分别测试了每个值,即format_it(df$Col1[1],1,"-")
,每个值都工作正常
但是,当我在 flextable 中设置一个set_formatter
时,
df %>%
flextable() %>%
set_formatter(Col1 = function(x) format_it(x,1,"-"))
我希望结果是正确的,但收到了错误的结果,
带有消息: the condition has length > 1 and only the first element will be used
我尝试更新以包含Vectorize
,但收到相同的错误
有什么建议么?
我想看看
我对你的功能有点困惑,但下面是一种以可重现的方式重新创建你的表(基于你的功能)的新代码方法,它会产生你想要的输出。 它首先将原始数据中的任何NA
值替换为“-”,然后使用grepl
检查所有非数值(即“hi”)并保持不变,然后使用sprintf
标准化数值中的有效数字。 这种方法在dplyr
“世界”中使用mutate()
和case_when()
并且没有使用用户定义的函数。
df %>%
mutate(Col1 = case_when(
is.na(Col1) ~ "-",
!grepl("[^A-Za-z]", Col1) ~ Col1,
grepl(".", Col1) ~ sprintf("%.1f", as.numeric(Col1)),
)) %>%
flextable::flextable()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.