简体   繁体   中英

How to group columns in 1 row and gather information in r?

I have this data.frame:

# Variable 1        Variable 2    Business(spec)
# Name Business     Macaco SA     NA
# ID Business       10            NA
# Type Business     Fishing       NA
# Name Business     Simio SA      NA
# ID Business       20            NA
# Type Business     Other         Transport

This was a file in excel that I imported to R. Variable 2 is a list of specific type of business. If the type of business is not in the list, in Business(Spec) they need to write the type of their business (so this variable can have different values). And i want to sort like this:

# Name Business    ID Business    Type Business    Business(spec)
# Macaco SA        10             Fishing          NA
# Simio SA         20             Other            Transport

I tried with pivot_wider(data, names_from = "Variable 1", values_from = "Variable 2") but it didn't work. How can I do this?

Thanks!!

If you can group things together (is it always 3 rows?), then you have a better chance.

I had to munge the data to use it more easily, so variable names and values are slightly different.

dat <- read.table(header=TRUE, stringsAsFactors=FALSE, text="
Variable1         Variable2     Business(spec)
Name_Business     Macaco_SA     NA
ID_Business       10            NA
Type_Business     Fishing       NA
Name_Business     Simio_SA      NA
ID_Business       20            NA
Type_Business     Other         Transport")

dat$grp <- cumsum(dat$Variable1 == "Name_Business")
dat
#       Variable1 Variable2 Business.spec. grp
# 1 Name_Business Macaco_SA           <NA>   1
# 2   ID_Business        10           <NA>   1
# 3 Type_Business   Fishing           <NA>   1
# 4 Name_Business  Simio_SA           <NA>   2
# 5   ID_Business        20           <NA>   2
# 6 Type_Business     Other      Transport   2
pivot_wider(dat, id_cols = "grp", names_from = "Variable1", values_from = "Variable2")
# # A tibble: 2 x 4
#     grp Name_Business ID_Business Type_Business
#   <int> <chr>         <chr>       <chr>        
# 1     1 Macaco_SA     10          Fishing      
# 2     2 Simio_SA      20          Other        

This makes an assumption that "Name_Business" is always the first within a grouping of rows, and that everything immediately after it is related to that row.

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