如何旋转单个单元格数据框

How to pivot a single cell dataframe

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

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)

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

我们可以用pivot_longermutate'red'来逻辑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  

在基础 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