R:在 for 循环中未用函数替换值

R : value not replaced in for loop with a function

我正在尝试创建一个列表,然后将其放入一个函数中。

我的问题是 "col" 永远不会被增量变量 (j) 替换。它仍然是 "j"。因此,在我的 for 循环结束时,当 j 为 11 时,列表中所有元素的所有 col 也是 j,所以如果我将它应用于我的函数,则为 11。

library(formattable)

x <- data.frame("value" = rep(1:5,2), "cats" = c(10,20,30,40,NA), "dogs" = c(15,25,35,36,48), "fish" = c(20,30,14,89,NA), "chicken"=c(14,23,12,9,3), "test"=c(TRUE,TRUE,FALSE, TRUE,FALSE))

l=list()
for (j in 1:ncol(x)) {
  if (is.na(x[nrow(x),j])) {
    l[[j]]=area(row=1:(nrow(x)-1), col=j) ~ color_bar(color = "#E0E0E0", na.rm = TRUE)
  } 
  else {
    l[[j]]=area(row=1:(nrow(x)-1), col=j) ~ color_bar(color = "#99CCFF", na.rm = TRUE)
  }
}
l
formattable(x, l)

可能是什么问题?

这是因为

The function creates an area object to store the representation of row and column selector expressions. When the function is called, the expressions and environment of row and column are captured for format_table to evaluate within the context of the input data.frame, that is,rownames and colnames are defined in the context to be the indices of rows and columns, respectively. Therefore, the row names and column names are available symbols when row and col are evaluate

(强调,来自 help("area"))。

因此它正在访问绑定到 符号 j.

的值

您要做的是向它传递一个公式,其中 valuej:

l=list()
for (j in 1:ncol(x)) {
    if (is.na(x[nrow(x),j])) {
        print("yes")
        l[[j]] <- as.formula(
            paste("area(row=1:(nrow(x)-1), col=", j, ") ~ color_bar(",
                  "color = \"#E0E0E0\", na.rm = TRUE)")
        )
    } 
    else {
        print("no")
        l[[j]] <- as.formula(
            paste("area(row=1:(nrow(x)-1), col=", j, ") ~ color_bar(",
                  "color = \"#99CCFF\", na.rm = TRUE)")
        )
    }
}
l
formattable(x, l)

更新:总体比例

默认情况下,使用这种方法,条形的大小将是列内比例。如果你想要整体比例,你可以将自定义 fun 参数传递给 color_bar(),如下所示:

l=list()
for (j in 1:ncol(x)) {
    if (is.na(x[nrow(x),j])) {
        print("yes")
        l[[j]] <- as.formula(
            paste("area(row=1:(nrow(x)-1), col=", j, ") ~ color_bar(",
                  "color = \"#E0E0E0\",",
                  "fun = function(y) y / max(x, na.rm = TRUE))")
        )
    } 
    else {
        print("no")
        l[[j]] <- as.formula(
            paste("area(row=1:(nrow(x)-1), col=", j, ") ~ color_bar(",
                  "color = \"#99CCFF\",",
                  "fun = function(y) y / max(x, na.rm = TRUE))")
        )
    }
}
l
formattable(x, l)