简体   繁体   中英

Mantain column names in map function with table

I have the following data stored in the object HRdata:

            ï..Employee_Name       PositionID              Position State  Zip
      1:   Adinolfi, Wilson  K         19  Production Technician I    MA 1960
      2: Ait Sidi, Karthikeyan         27                  Sr. DBA    MA 2148
      3:     Akinkuolie, Sarah         20 Production Technician II    MA 1810
      4:          Alagbe,Trina         19  Production Technician I    MA 1886
      5:       Anderson, Carol         19  Production Technician I    MA 2169
     ---                                                                     
    307:        Woodson, Jason         20 Production Technician II    MA 1810
    308:     Ybarra, Catherine         19  Production Technician I    MA 2458
    309:      Zamora, Jennifer          6                      CIO    MA 2067
    310:           Zhou, Julia          9             Data Analyst    MA 2148
    311:         Zima, Colleen         19  Production Technician I    MA 1730

I am using a map function to table the unique instances in each variable within the data.frame.

HRtables <- map(tibble(HRdata), ~as.data.frame(sort(table(.x), decreasing = T, responseName = "n")))

It makes a list just fine but the output is not to my liking:

    > HRtables$State
   .x Freq
1  MA  276
2  CT    6
3  TX    3
4  VT    2
5  AL    1
6  AZ    1
7  CA    1
8  CO    1
9  FL    1
10 GA    1
11 ID    1
12 IN    1
13 KY    1

Is there any way I can keep the original name of the variable instead of it being replaced with.x?

I suppose you could pass in the column names of your data.frame using map2 . Then you could include dnn argument for table that would include the column name. Perhaps something like this might work for you.

library(tidyverse)

map2(HRdata,
     names(HRdata),
     ~as_tibble(sort(table(.x, dnn = .y), decreasing = T)))

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