简体   繁体   English

将行转换为列,然后使用 R 堆叠成单列

[英]Turn rows to columns, then stack into single column using R

I have a dataframe of data which I need to convert to use for a panel study.我有一个数据数据框,我需要将其转换为用于小组研究。 I want to convert my rows into columns, then stack the columns into a single column.我想将我的行转换为列,然后将列堆叠成一列。 My current data:我目前的数据:

STATE    1970   1971   1972   1973...2018
State-A  X      X      X      X       X
State-B  X      X      X      X       X
State-C  X      X      X      X       X

What I need:我需要的:

Year   State  Data
1970    A      X
1971    A      X
...
2018    A      X
1970    B      X
1971    B      X

etc...等等...

I have tried the stack, and melt, and reshape functions to no avail.我已经尝试过堆栈、融化和重塑功能都无济于事。 I also tried to list my data then flatten it, which was a total disaster.我还尝试列出我的数据然后将其展平,这完全是一场灾难。 Any help is much appreciated!任何帮助深表感谢!

We can use tidyverse我们可以使用tidyverse

library(dplyr)
library(tidyr)
df1 %>%
     pivot_longer(cols = -Year, values_to = 'Data') %>% 
    c
# A tibble: 12 x 3
#   Year  State Data 
#   <chr> <chr> <chr>
# 1 1970  A     X    
# 2 1971  A     X    
# 3 1972  A     X    
# 4 1973  A     X    
# 5 1970  B     X    
# 6 1971  B     X    
# 7 1972  B     X    
# 8 1973  B     X    
# 9 1970  C     X    
#10 1971  C     X    
#11 1972  C     X    
#12 1973  C     X 

Update更新

With the updated example, change is使用更新的示例,更改是

df1 %>%
   pivot_longer(cols = -STATE, names_to = 'Year', values_to = 'Data')

If package version of tidyr is old, use gather如果tidyr软件包版本tidyr旧,请使用gather

df1 %>%
    gather(name, Data, -Year) %>%
    separate(Year, into = c('other', 'State')) %>%
    select(Year = name, State, Data)

Or with melt或者用melt

library(data.table)
melt(setDT(df1), id.var = 'Year', value.name = 'Data')[, 
    .(State = sub('.*-', '', Year), Year = variable, Data)]

data数据

df1 <- structure(list(Year = c("State-A", "State-B", "State-C"), `1970` = c("X", 
"X", "X"), `1971` = c("X", "X", "X"), `1972` = c("X", "X", "X"
), `1973` = c("X", "X", "X")), class = "data.frame", row.names = c(NA, 
-3L))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM