我有这样的data.frame:
df<-data.frame(Time=c(1:100),Rome_population=c(1:100),Rome_gdp=c(1:100),Rome_LifeLenght=c(1:100),London_population=c(1:100),London_gdp=c(1:100),London_LifeLenght=c(1:100),Berlin_population=c(1:100),Berlin_gdp=c(1:100),Berlin_LifeLenght=c(1:100))
我想要一个像这样的data.frame: df <-data.frame(时间,城市,人口,gdp,LifeLenght)
我该怎么做?可能是提迪尔?
谢谢!
答案 0 :(得分:1)
尝试:
df %>%
gather(key, value, Rome_population:Berlin_LifeLenght) %>%
separate(key, into = c("city", "stat"), sep = "_") %>%
spread(stat, value)
输出:
# A tibble: 300 x 5
Time city gdp LifeLenght population
<int> <chr> <int> <int> <int>
1 1 Berlin 1 1 1
2 1 London 1 1 1
3 1 Rome 1 1 1
4 2 Berlin 2 2 2
5 2 London 2 2 2
6 2 Rome 2 2 2
7 3 Berlin 3 3 3
8 3 London 3 3 3
9 3 Rome 3 3 3
10 4 Berlin 4 4 4
# ... with 290 more rows