如何旋转单个单元格数据框 [英] 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
但是 red
是变量 fruit
的一个属性,而 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?
推荐答案
在基础 R 中你会这样做:
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
这篇关于如何旋转单个单元格数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文