我想跨列移动并根据数据表单元格中的值附加文本。
这是当前的表格:
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列中,Under不应该
\\cellcolor333 it should just be \\cellcolor
正确的方法是什么?
答案 0 :(得分:2)
最好使用对整个矢量同时运行的矢量化函数。 if
不会这样做,但ifelse()
会这样做。尝试
as.data.frame(lapply(table[, 1:3], function(x) {
paste0("\\cellcolor", ifelse(x=="Under","","333"), "{", x, "}")
}))
答案 1 :(得分:1)
以下代码对您的问题进行了回答:
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}"
table
与table[,1:3]
相同。 apply
的第二个参数是2,因此函数中的x
是表的每一列,即。两个元素的向量,如果不将向量作为条件,也不返回向量,因此您需要使用 ifelse()函数。