問題描述
如何將行值更改為列名 (R) (How change Row values to Column names (R))
我正在處理 COVID19 數據。有一個不便之處。我有一個名為 location 的列,所有國家都在該列下。為了說明,第一個值是國家 A、日期 A、下一個國家 A、日期 B...國家 Z、日期 Z。我想知道如何按日期對所有值進行分組並將每個國家作為單獨的列?
這是數據的鏈接:
https://ourworldindata .org/coronavirus‑source‑data
參考解法
方法 1:
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 (i.e., 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
(by Tigran Danielyan、Haci Duru)