简体   繁体   中英

Use dataframe attr within 2 function lapply

I wrote a function to create a div using the name of each column in a data frame. I want the text of the div to be the data frame's "labels" attr

library(shiny)

df <- data.frame(x = c(1, 2, 3), y = c(4, 5, 6), z = c(7, 8, 9))
attr(df$x, "labels") <- "a"
attr(df$y, "labels") <- "b"
attr(df$z, "labels") <- "c"

rowBlocks <- function(data, name, label)
{
  div(
    drag = name,
    div(class = "active-title", id = name, label))
}

lapply(sort(colnames(df[,1:3])), rowBlocks, 
       #Rather than have "Text below, 
       # How do I get the df attr "label" on hover?
                 data = df, label = "Text")

I wasn't sure how to phrase this question but I think I need to use an lapply with two functions, and I'm also struggling to access the attr within an lapply.

Desired Output

[[1]]
<div drag="x">
  <div class="active-title" id="x">a</div>
</div>

[[2]]
<div drag="y">
  <div class="active-title" id="y">b</div>
</div>

[[3]]
<div drag="z">
  <div class="active-title" id="z">c</div>
</div>

I tried using label = attr(df$name, "label") but it interprets name literally, not using the actual name variable... Any help appreciated!

You can either change your rowBlocks function to look up the labels for you from the data

rowBlocks <- function(data, name){
  div(
    drag = name,
    div(class = "active-title", id = name, attr(data[[name]],"labels")))
}

lapply(sort(colnames(df[,1:3])), rowBlocks, 
       data = df)

or you could change how you are calling it to iterate over the names and labels

rowBlocks <- function(name, label){
  div(
    drag = name,
    div(class = "active-title", id = name, label))
}
cols <- sort(colnames(df[,1:3]))
Map(rowBlocks, cols, sapply(cols, function(x) attr(df[[x]], "labels")))

Here we use Map rather than lapply because we need to loop over multiple inputs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM