简体   繁体   中英

Print labels and variable names with head

I am trying to use something like the head command in R, but also include the variable labels in the output to the console.

So far I have tested both head() and dplyr::slice() with data.frames and tibbles but nothing has the options to display labels as well as the column names.

Does anyone know if this is possible to do?

I'm trying to get something like this:

# A tibble: 3 x 21
SiteSeq   SiteName  SiteCode  SubjectSeq   SubjectId    EventSeq 
<Site No> <Name>    <Code>    <Patient No> <Patient ID> <Event No> 
2         Peter M~   PMC       1           PMC-001      1        
2         Peter M~   PMC       1           PMC-001      1        
2         Peter M~   PMC       1           PMC-001      1 

Where the things in <> are the column labels.

I know the labels are viewable with View() , but I am just wondering if there is also a way to see them in the console. Thanks!

Edit:

All variables are labelled using the Hmisc::label() command just after reading in the data. Eg, label(data$variable1) <- "label1"

Thanks to the advice from @MRau here is a simple function that will print the labels along with the variable names when viewing in the console:

lhead <- function(df, n=7){  

  is.Date <- function(x){
    ifelse(inherits(x, c("POSIXt", "POSIXct", "Date")), TRUE, FALSE)
  }

  df2 <- df
  df2[sapply(df2, is.factor)] <- lapply(df2[sapply(df2, is.factor)], as.character)
  df2[sapply(df2, is.Date)] <- lapply(df2[sapply(df2, is.Date)], as.character)
  tmp <- rbind(label(df), df2)
  head(tmp, n)  
}

Edit:

Had issues with dates so included extra date bit

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