I am working with dataframes in R and I would like to change the format of table 1 (image1), to the table 2 (image2).
I know that i have 50 'City' possible values, from 1 to 50. What i want is that those values of 'City' become different columns, so below each of these values the number of 'House' is shown. Finally i would have only one row for every Country, and 52 columns. ('Number','Country',1,2,3...,50). (This is a simplify version, the main one has much more values of 'Number', so i am looking for a solution that works 'fast', that does not take long for running)
If df is your dataframe and columns are lowercase the following dplyr::pivot_wider will help you.
library(dplyr)
df %>%
pivot_wider(id_cols=c(number,country),names_from=city,values_from=house)
To give you this output.
# A tibble: 3 × 7
number country `21` `23` `24` `22` `25`
<int> <int> <chr> <chr> <chr> <chr> <chr>
1 6205 2 2 a 5 NA NA
2 6205 3 NA 5 5 1 5
3 6205 4 4 2 7 3 2
>
Its advisable to not use numeric dataframe column names, hence ideal to re-look at your naming conventions.
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.