How to pivot a single cell dataframe

↘锁芯ラ 提交于 2021-02-19 12:51:36

问题


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?


回答1:


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



回答2:


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  


来源:https://stackoverflow.com/questions/65498598/how-to-pivot-a-single-cell-dataframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!