Emman
Emman

Reputation: 4201

How to pivot a single cell dataframe

I have encountered such a simple challenge, and yet don't know how to do this properly.

library(tibble)
library(dplyr)


# I have this single-cell dataframe

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

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

But being red is a property of the variable fruit, which apple is one observation of. Therefore, I want my data to look like:

# Desired Output:

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

So I tried a clunky method, which seems not best practice:

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

Is there a proper way to do it? Perhaps by pivoting rather than mutating and renaming?

Upvotes: 1

Views: 51

Answers (2)

Onyambu
Onyambu

Reputation: 79288

In base R you would do:

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

And if you need it as a dataframe:

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

Note that this would work even when you have multiple colors and fruis: eg:

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

Upvotes: 3

akrun
akrun

Reputation: 887541

We can use pivot_longer and mutate the 'red' to logical TRUE

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

-output

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

Or another option is 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  

Upvotes: 1

Related Questions