【问题标题】:convert column names into a new row [duplicate]将列名转换为新行[重复]
【发布时间】:2021-05-15 18:10:32
【问题描述】:

我有一个code,如下所示,它与mtcars 完美配合,但我想知道是否有比将Species 列转换为字符更好的解决方案。非常感谢提前

df <- head(iris); df
rbind(newRow = colnames(df), df) 

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

【问题讨论】:

  • 其他列呢?它也转换为字符
  • 我同意@akrun。一般来说,除非非常必要,否则我不会尝试将charactersnumeric 变量“混合”。因为它使一切character。 @SeymaKalay 为什么要将所有内容保留为 character 而将 Species 列保留为 factor
  • 这是代码链接中的建议,但我正在寻找更有效的方法,如果有的话。
  • 这与您已经发布的问题有何不同?

标签: r tidyverse tidyr data-manipulation


【解决方案1】:

我们也可以

library(data.table)
rbindlist(list(as.list(names(df)), df))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-06
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2019-10-14
    • 1970-01-01
    相关资源
    最近更新 更多