简体   繁体   中英

How change Row values to Column names (R)

I am working with COVID19 data. There is one inconvenience. I have a column named location and all countries are under that column. To illustrate, first value is Country A, Date A, next Country A, Date B... Country Z, Date Z. I wonder how can I group all the values by dates and have each country as a separate column?

This is the link of the data:

https://ourworldindata.org/coronavirus-source-data

You can reshape the data using code like the following:

df_example = with(df, data.frame(location = location,
                                date = date, 
                                new_cases = new_cases))

df_example = reshape(df_example, timevar = "location", idvar = "date", direction = "wide")
df_example = df_example[order(df_example$date), ]

Note here that I kept only one variable as the cell value in the new data frame (ie, new_cases), because the new data frame is already very wide (it has 213 columns now). If you keep additional variables the new data frame will be wider.

head(df_example)   # I will not put the output here, you can try yourself

The following three lines will make the new data frame look nicer.

cnames = names(df_example)[2:ncol(df_example)]
cnames = unlist(lapply(cnames, function(x) substr(x, 11, nchar(x))))
names(df_example)[2:ncol(df_example)] = cnames

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