R 使用apply附加结果混乱的文本

R 使用apply附加结果混乱的文本,r,R,我希望跨列移动,并根据数据表单元格中的值追加文本 以下是当前表格: table = data.frame( c1 = c("Under","Over"), c2 = c("Under", "Over") , c3 = c("NA","Under")) apply( table[, 1:3], 2, function(x) { if(x=="Under"){ paste0("\\cellcolor{", x, "}") }else

我希望跨列移动,并根据数据表单元格中的值追加文本

以下是当前表格:

table = data.frame(
    c1 = c("Under","Over"), 
    c2 = c("Under", "Over") , 
    c3 = c("NA","Under"))  
apply(  table[, 1:3],  2,  function(x)  {
   if(x=="Under"){
       paste0("\\cellcolor{", x, "}")
    }else{ 
       paste0("\\cellcolor333{", x, "}")
   }
 })
目前,这不起作用,因为在第3列中,不应该有

\\cellcolor333 it should just be \\cellcolor

正确的方法是什么?

最好使用一次操作整个向量的向量化函数
if
不执行此操作,但
ifelse()执行此操作。试一试

as.data.frame(lapply(table[, 1:3], function(x)  {
       paste0("\\cellcolor", ifelse(x=="Under","","333"), "{", x, "}")
}))
答复 以下代码回答了您的问题:

apply(table,  2,  function(x)  ifelse(x=="Under",paste0("\\cellcolor{", x, "}"),paste0("\\cellcolor333{", x, "}")))
     c1                     c2                     c3                  
[1,] "\\cellcolor{Under}"   "\\cellcolor{Under}"   "\\cellcolor333{NA}"
[2,] "\\cellcolor333{Over}" "\\cellcolor333{Over}" "\\cellcolor{Under}"
解释
表格
表格[,1:3]
相同。
apply
的第二个参数是2,因此函数中的
x
是表中的每一列,即两个元素的向量,if既不以向量作为条件,也不返回向量作为结果,因此需要使用ifelse()函数。

您的问题是使用的是
if(x=='Under')
在长度为
length(x)>1的向量上,因此只使用列的第一个元素。
c3
的第一个元素是否等于“
下的