[英]condition has length > 1 and only the first element r
I have我有
df = data.frame(Col1 = c( NA, 1," ", 2345.768,"hi","", NA, 3.4, "44.99"))
and want to format specific values, and created a udf并想要格式化特定值,并创建了一个 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))}
}
I tested each value individually, ie format_it(df$Col1[1],1,"-")
, and each one worked ok我分别测试了每个值,即
format_it(df$Col1[1],1,"-")
,每个值都工作正常
but, when I set up a set_formatter
in flextable,但是,当我在 flextable 中设置一个
set_formatter
时,
df %>%
flextable() %>%
set_formatter(Col1 = function(x) format_it(x,1,"-"))
I hoped the results would be correct, but received the wrong results,我希望结果是正确的,但收到了错误的结果,
with the message: the condition has length > 1 and only the first element will be used
带有消息:
the condition has length > 1 and only the first element will be used
I tried updating to include Vectorize
, but received the same error我尝试更新以包含
Vectorize
,但收到相同的错误
Any suggestions?有什么建议么?
I would like to see我想看看
I'm a little confused on your function, but a fresh code approach to recreating your table (based on your function) in a reproducible way is below, which produces your desired output.我对你的功能有点困惑,但下面是一种以可重现的方式重新创建你的表(基于你的功能)的新代码方法,它会产生你想要的输出。 It first replaces any
NA
values in the original data with "-", then checks for all non-numeric values (ie, "hi") using grepl
and keeps those the same, then standardizes the significant digits in the numeric values with sprintf
.它首先将原始数据中的任何
NA
值替换为“-”,然后使用grepl
检查所有非数值(即“hi”)并保持不变,然后使用sprintf
标准化数值中的有效数字。 This approach was within the dplyr
"world" using mutate()
and case_when()
and did not use a user-defined function.这种方法在
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.