【问题标题】:How do I convert a column in my data into the rows in R [duplicate]如何将数据中的列转换为 R 中的行 [重复]
【发布时间】:2022-01-10 20:16:07
【问题描述】:

我正在处理一些特定国家/地区的信息,现在,我的数据如下所示:

score country      code  prev.score
  1    Brazil      BRA      5
  2    Singapore   SIN      3
  3    France      FRA      4

如何将国家/地区转换为数据的焦点,理想情况下如下所示:

          Score Code  prev.score
Brazil     1    Bra    5
Singapore  2    SIN    3
France     3    FRA    4

谢谢。

【问题讨论】:

  • df %>% select(country, everything()) 如果要保留列名。 df %>% column_to_rownames(country) 否则。

标签: r dplyr


【解决方案1】:

您可以使用tibble::column_to_rownames

library(tibble)

tibble::column_to_rownames(df, "country")

输出

          score code prev.score
Brazil        1  BRA          5
Singapore     2  SIN          3
France        3  FRA          4

数据

df <-
  structure(
    list(
      score = c(1, 2, 3),
      country = c("Brazil", "Singapore",
                  "France"),
      code = c("BRA", "SIN", "FRA"),
      prev.score = c(5, 3,
                     4)
    ),
    class = "data.frame",
    row.names = c(NA,-3L)
  )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 2018-02-21
    • 2018-11-06
    • 2018-04-26
    • 2020-02-16
    • 1970-01-01
    • 2019-10-14
    相关资源
    最近更新 更多