【问题标题】:How to create a one-row data.frame (tibble) from 2 vectors. One with the desired column names, and another with the values for the row?如何从 2 个向量创建单行 data.frame (tibble)。一个带有所需的列名,另一个带有行的值?
【发布时间】:2021-12-21 06:48:45
【问题描述】:

我在 R 中有两个相同大小的字符向量。我们称它们为variablesvalues(它们的元素数量相同)。

我希望从这两个向量中创建一个单行 data.frame (tibble)。其中列名是variables,行中的实际值为values

我该怎么做?

【问题讨论】:

    标签: r dataframe tibble


    【解决方案1】:

    您可以创建一个命名向量并将其拼接以用于tibble()

    values <- 1:3
    variables <- LETTERS[1:3]
    
    library(tibble)
    
    tibble(!!!setNames(values, variables))
    
    # A tibble: 1 x 3
          A     B     C
      <int> <int> <int>
    1     1     2     3
    

    【讨论】:

    • 我不知道!!! 代表什么,但我会寻找它
    【解决方案2】:
    library(tidyverse)
    
    variables <- letters[1:3]
    variables
    #> [1] "a" "b" "c"
    
    values <- seq(3)
    values
    #> [1] 1 2 3
    
    data.frame(variables, values) %>%
       pivot_wider(names_from = variables, values_from = values)
    #> # A tibble: 1 x 3
    #>       a     b     c
    #>   <int> <int> <int>
    #> 1     1     2     3
    

    reprex package 创建于 2021-11-08 (v2.0.1)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 2014-11-22
      • 1970-01-01
      • 2020-07-19
      相关资源
      最近更新 更多