如何在保持元素顺序的同时转置数据框中的列?

How to transpose a column in a dataframe while keeping the order of the elements?

  OECD2012  GDP2012 GDP2012born  countrynew countrybornText permile
1        1 56149.67    50632.44 Switzerland   United States       3
2        1 56149.67    45948.54 Switzerland     Netherlands       2
3        1 56149.67    44829.27 Switzerland         Ireland       1
4        1 56149.67    44551.62 Switzerland         Austria       9
5        1 56149.67    44336.81 Switzerland         Denmark       3
6        1 56149.67    43355.81 Switzerland          Sweden       1

您好,我的数据是这样的,我需要将其制成矩阵。所以我 运行 以下内容:

df2 <- df %>% spread(key = countrybornText, value = permile)

我的问题是我希望列按 GDP2012born 排序,并且在我转置时它们按字母顺序显示。知道如何保持我在 countrybornText 列中的顺序吗?

df <- structure(list(OECD2012 = c(1, 1, 1, 1, 1, 1), GDP2012 = c(56149.67, 
      56149.67, 56149.67, 56149.67, 56149.67, 56149.67), GDP2012born = c(50632.44, 
      45948.54, 44829.27, 44551.62, 44336.81, 43355.81), countrynew = structure(c(1L, 
      1L, 1L, 1L, 1L, 1L), .Label = "Switzerland", class = "factor"), 
      countrybornText = structure(c(6L, 4L, 3L, 1L, 2L, 5L), .Label = c("Austria", 
      "Denmark", "Ireland", "Netherlands", "Sweden", "United States"), 
      class = "factor"), permile = c(3, 2, 1, 9, 3, 1)), class = "data.frame", 
      row.names = c(NA, -6L))

您可以确保该列是一个因子,其水平按您想要的顺序排列:

library(dplyr)
library(tidyr)

df$countrybornText <-factor(as.character(df$countrybornText), as.character(df$countrybornText))
df2 <- df %>% spread(key = countrybornText, value = permile)

df2
#>   OECD2012  GDP2012 GDP2012born  countrynew United States Netherlands Ireland
#> 1        1 56149.67    43355.81 Switzerland            NA          NA      NA
#> 2        1 56149.67    44336.81 Switzerland            NA          NA      NA
#> 3        1 56149.67    44551.62 Switzerland            NA          NA      NA
#> 4        1 56149.67    44829.27 Switzerland            NA          NA       1
#> 5        1 56149.67    45948.54 Switzerland            NA           2      NA
#> 6        1 56149.67    50632.44 Switzerland             3          NA      NA
#>   Austria Denmark Sweden
#> 1      NA      NA      1
#> 2      NA       3     NA
#> 3       9      NA     NA
#> 4      NA      NA     NA
#> 5      NA      NA     NA
#> 6      NA      NA     NA

reprex package (v0.3.0)

于 2020-02-18 创建