Conditional formatting of cells in a table based on the value of the cells?

Hi,
I’m trying to create a table from data in a csv file. The first two rows and 1st column are headings which I want to color differently and this code works fine:

#let sensitivity_table = for file in sets.files {
	let fileData = csv(data_dir + file + ".csv")
	let numRows = fileData.len()
	makefigure(
		kind: table,
		{
			heading(file)
			maketable(
				fileData,
				fill: (x, y) => if y < 2 or x < 1 { yellow } ,    
			)

		},
	)
}

I also want to color any cells that contain ‘nan’ red and I can’t seem to figure out the syntax. I have tried things like:

                    maketable(
                      fileData,
                      fill: (x, y, fileData) => {
                        if y < 2 or x < 1 {
                          yellow
                        } 
                        else if fileData[y][x] == "nan" { red }  
                        else { none }
                      }
                    )

and

maketable(
  fileData,
  fill: (x, y) => {
    if y < 2 or x < 1 {
      yellow
    } else if str(fileData[y][x]).lower() == 'nan' {
      red  
    } else {
      none 
    }
  }
)

But neither works. Does anyone know the correct syntax to do this ?

Thanks

It would be great if you could say more about what the error message is and more about in which way it doesn’t work (expected vs actual result).

One thing I spot is that fileData[y][x] is not the syntax for indexing an array, you should use fileData.at(y).at(x). And remember that if you have a header row in the table, then you need to offset the y index for that.

Hi Bluss,

Yes, this solved the problem thanks. All the other syntax I tried just resulted in failed compilation. For reference, with the incorrect indexing syntax I got:

error: expected function, found array
   ┌─ chapters/sensitivity/conf.typ:47:36
   │
47 │                             else if fileData[y][x] == "nan" or fileData[y][x] == "inf" { red }
   │                                     ^^^^^^^^

help: error occurred in this call of function `table`
    ┌─ lib.typ:146:8
    │  
146 │ ╭         table(
147 │ │             ..table_args,
148 │ │             columns: n_columns,
149 │ │             table.header(
    · │
152 │ │             ..matrix.slice(n_row_headers).flatten(),
153 │ │         )
    │ ╰─────────^

I interpretted this to mean that arrays weren’t allowed in the if… else… conditions. I guess error messages can confusing when I use incorrect syntax.
Thanks,

1 Like

the problem is that foo[x] is valid syntax: it is equivalent to foo([x]), i.e. a function call taking a content block as a parameter. So if foo is not a function, that’s not allowed: “expected function, found array”