【问题标题】:Reshape dataframe in R using values in 1 column as column names in new dataframe使用 1 列中的值作为新数据框中的列名重塑 R 中的数据框
【发布时间】:2021-07-17 00:51:59
【问题描述】:

我认为这是一个非常直接的重塑,尽管我们正在努力。我们有这个数据框:

structure(list(X1 = c("Title:", "Phone:", "Email:", "Previous College:"
), X2 = c("Head Coach, Year2", "123-456-7890", "name@email.com", 
          "The Best")), class = "data.frame", row.names = c(NA, 
                                                                     -4L))

                 X1                X2
1            Title: Head Coach, Year2
2            Phone:      123-456-7890
3            Email:    name@email.com
4 Previous College:          The Best

我们正在尝试将其转换为 1 行数据框,如下所示:

data.frame(Title = 'Head Coach, Year2', Phone = '123-456-7890', Email = 'name@email.com', `Previous College` = 'The Best', stringsAsFactors = FALSE)

              Title        Phone          Email Previous.College
1 Head Coach, Year2 123-456-7890 name@email.com         The Best

【问题讨论】:

    标签: r data-manipulation


    【解决方案1】:

    我们可以deframe 并转换为 tibble

    library(dplyr)
    library(stringr)
    library(tibble)
    df1 %>%
        mutate(X1 = str_remove(X1, ":")) %>%
        deframe %>%
        as_tibble_row
    # A tibble: 1 x 4
      Title             Phone        Email          `Previous College`
      <chr>             <chr>        <chr>          <chr>             
    1 Head Coach, Year2 123-456-7890 name@email.com The Best          
    

    或使用base R,通过使用'X1'列设置名称并使用as.data.frame.list将命名的vector转换为data.frame

    as.data.frame.list(with(df1, setNames(X2, trimws(X1, 
            whitespace = ":"))), check.names = FALSE)
                  Title        Phone          Email Previous College
    1 Head Coach, Year2 123-456-7890 name@email.com         The Best
    

    data.table::transpose

     data.table::transpose(df1, make.names = 'X1')
                 Title:       Phone:         Email: Previous College:
    1 Head Coach, Year2 123-456-7890 name@email.com          The Best
    

    【讨论】:

      【解决方案2】:

      你也可以这样做:

      read.dcf(textConnection(do.call(paste, df)), all = TRUE)
                    Title        Phone          Email Previous College
      1 Head Coach, Year2 123-456-7890 name@email.com         The Best
      

      【讨论】:

        【解决方案3】:

        使用data.table 的另一种方法-

        library(data.table)
        
        dcast(setDT(df), rowid(X1)~sub(':', '', X1, fixed = TRUE), value.var = 'X2')
        
        #   X1          Email        Phone Previous College             Title
        #1:  1 name@email.com 123-456-7890         The Best Head Coach, Year2
        

        【讨论】:

          猜你喜欢
          • 2021-08-12
          • 2015-09-30
          • 1970-01-01
          • 1970-01-01
          • 2014-10-10
          • 1970-01-01
          • 2017-04-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多