【问题标题】:How to pivot a single cell dataframe如何旋转单个单元格数据框
【发布时间】:2021-04-06 11:07:38
【问题描述】:

我遇到了这么简单的挑战,但不知道如何正确地做到这一点。

library(tibble)
library(dplyr)


# I have this single-cell dataframe

tibble::tribble(~red,
                "apple")

## # A tibble: 1 x 1
##   red  
##   <chr>
## 1 apple

但是red 是变量fruit 的一个属性,apple 是其中的一个观察值。因此,我希望我的数据看起来像:

# Desired Output:

## # A tibble: 1 x 2
##   fruit red  
##   <chr> <lgl>
## 1 apple TRUE 

所以我尝试了一种笨拙的方法,这似乎不是最佳实践:

tibble::tribble(~red,
                "apple") %>%
  mutate(is_red = TRUE) %>%
  rename(fruit = red, red = is_red)

有合适的方法吗?也许通过旋转而不是变异和重命名?

【问题讨论】:

    标签: r tidyr tibble


    【解决方案1】:

    我们可以使用pivot_longermutate '红色' 到逻辑TRUE

    library(dplyr)
    library(tidyr)
    df1 %>%
        pivot_longer(everything(), names_to = names(.), values_to = 'fruit') %>%
         mutate(!! names(df1) := TRUE)
    

    -输出

    # A tibble: 1 x 2
    #  red   fruit
    #  <lgl> <chr>
    #1 TRUE  apple
    

    或者另一个选项是cur_column

    df1 %>% 
      mutate(across(everything(), ~cur_column(), .names = "fruit"),
             !! names(df1) := TRUE)
    # A tibble: 1 x 2
    #   red   fruit
    #   <lgl> <chr>
    #1 TRUE  red  
    

    【讨论】:

    • 谢谢。但是我们不能将列名传递给names_to,而不是硬编码“红色”字吗?
    • @Emman 我更新了帖子。但是,这可能不是一个通用的解决方案,即当您有更多的列和行时
    【解决方案2】:

    在基础 R 中你会这样做:

    table(stack(df))>0
           ind
    values   red
      apple TRUE
    

    如果您需要它作为数据框:

    as.data.frame.matrix(table(stack(df)) > 0)
           red
    apple TRUE
    

    请注意,即使您有多种颜色和水果,这也会起作用: 例如:

    df1=data.frame(red= 'apple', green = 'apple', orange = 'orange', yellow = 'banana') 
    
    as.data.frame.matrix(table(stack(df1)) > 0)
             red green orange yellow
    apple   TRUE  TRUE  FALSE  FALSE
    banana FALSE FALSE  FALSE   TRUE
    orange FALSE FALSE   TRUE  FALSE
    

    【讨论】:

    • 这真是太好了。我想知道是否有办法使用%&gt;% 进行管道传输。因为这是更大工作流程的一部分,所以我尽量不要在此过程中分配额外的数据对象。现在,运行 df %&gt;% as.data.frame.matrix(table(stack(.)) &gt; 0) 会引发错误。你知道如何使用%&gt;% 进行这项工作吗?
    • @Emman df %&gt;% stack() %&gt;%table() %&gt;% as.data.frame()%&gt;%is_greater_than(0) 应该可以工作,或者如果你愿意,你可以这样做df %&gt;% {as.data.frame.matrix(table(stack(.)) &gt; 0)}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多