如何將行值更改為列名 (R) (How change Row values to Column names (R))


問題描述

如何將行值更改為列名 (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 DanielyanHaci Duru)

參考文件

  1. How change Row values to Column names (R) (CC BY‑SA 2.5/3.0/4.0)

#R #dataframe






相關問題

如何將均值、標準差等函數應用於整個矩陣 (How to apply mean, sd etc. function to a whole matrix)

Tạo các thùng của mỗi hàng trong bảng và vẽ hình thanh ngăn xếp trong R (Make bins of each table row and draw stack bar figure in R)

Reading not quite correct .csv file in R (Reading not quite correct .csv file in R)

包'treemap'中的線條粗細 (Thickness of lines in Package ‘treemap’)

是否需要帶有 awk 的預處理文件,或者可以直接在 R 中完成? (Is preprocessing file with awk needed or it can be done directly in R?)

rpivotTable 選擇元素下拉菜單 (rpivotTable select elements drop down menu)

優化性能 - Shiny 中的大文件輸入 (Optimizing Performance - Large File Input in Shiny)

數值取決於所應用的應用系列,R (Numeric values depending of apply family applied, R)

如何記錄全年的值? (How to note the values across year?)

R中的線性搜索 (Linear search in R)

在 dplyr/purrr 工作流程中動態連接多個數據集 (Dynamically join multiple datasets in a dplyr/purrr workflow)

如何將行值更改為列名 (R) (How change Row values to Column names (R))







留言討論