将行转换为单列

converting rows into a single column

year  Pink Floyd Metallica Rammstein Led Zeppelin Pantera     
2004  600        700        500        400        300
2005  700        300        400        200        500
2006  300        150        600        700        700

大家好。我有一个与我提到的类似的数据。每个组现在都是一个单独的列。我想在组的名称下打开一个新列,并将年份放入行中。我的意思是:

Bands       2004  2005  2006
Pink Floyd  600   700   300
Metallica   700   300   150
Rammstein

不是波段,我的原始数据是77个城市,16年。所以我的真实数据中有 78 个变量,77 个不同的城市和一年。因此,我可以说我正在处理大量数据。所以,我需要你的帮助。

您可以转置数据框然后更改名称。像这样:

library(tidyr)
# Let be df your dataframe
df <- data.frame(year = c(2005,2005,2006), PinkFloyd = c(600, 700, 300), Metallica = 
c(700,300,150),  Ramstein =c(500,400,600), LedZepelin =c(400,200,700), Pantera=c(300,500,700) ) 

#Transpose data and change names
df_aux <- data.frame(t(df))
colnames(df_aux ) <- unique(df$year)
df_aux <- df_aux[-1,]
df_aux <- tibble::rownames_to_column(df_aux, "Band")

结果是:

> df_aux 
 Band        2005 2004 2006
 PinkFloyd   600  700  300
 Metallica   700  300  150
 Ramstein    500  400  600
 LedZepelin  400  200  700
 Pantera     300  500  700

我们可以使用pivot_longer and pivot_wider from the tidyr包。

library(tidyverse)
df %>%
    pivot_longer(cols = -year, names_to = "band") %>%
    pivot_wider(names_from = year, values_from = value)

#   band       `2004` `2005` `2006`
# 1 PinkFloyd     600    700    300
# 2 Metallica     700    300    150
# 3 Rammstein     500    400    600
# 4 LedZepelin    400    200    700
# 5 Pantera       300    500    700

这是一个使用 transpose

data.table 选项
> data.table::transpose(setDT(df), keep.names = "Band", make.names = "year")
           Band 2004 2005 2006
1:   Pink Floyd  600  700  300
2:    Metallica  700  300  150
3:    Rammstein  500  400  600
4: Led Zeppelin  400  200  700
5:      Pantera  300  500  700

数据

> dput(df)
structure(list(year = 2004:2006, `Pink Floyd` = c(600L, 700L, 
300L), Metallica = c(700L, 300L, 150L), Rammstein = c(500L, 400L,
600L), `Led Zeppelin` = c(400L, 200L, 700L), Pantera = c(300L,
500L, 700L)), class = c("data.table", "data.frame"), row.names = c(NA,
-3L))