我遇到了这样一个简单的挑战,但却不知道如何正确地做到这一点。
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)有什么合适的方法吗?也许是通过旋转而不是变异和重命名?
发布于 2020-12-29 20:54:09
在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发布于 2020-12-29 20:51:37
我们可以使用pivot_longer和mutate将“红色”转换为逻辑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或者另一个选择是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
复制相似问题