gpt4 book ai didi

r - 在数据框中创建存在/不存在列

转载 作者:行者123 更新时间:2023-12-04 14:35:28 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Create numerically encoded dummy variables efficiently in R?

(3 个回答)


去年关闭。




我有一个数据框看起来或多或少像这样

df <- tribble(
~Species, ~Symbiont, ~Location,
"a", "s01", "P01",
"b", "s02", "P01",
"c", "s01", "P02",
"a", "s03", "P03",
"d", "s02", "P02",
"c", "s04", "P04",
"a", "s03", "P01",
"c", "s02", "P02",
"c", "s03", "P02"
)
我想要实现的是每个 Species 都有一行在每个 Location ,以及关于 Symbiont 的存在-不存在 0-1 信息.
例如,对于给定的数据,

Species s01 s02 s03 s04 Location
a 1 0 1 0 P01
a 0 0 1 0 P03
b 0 1 0 0 P02
c 1 1 1 0 P02
c 0 0 0 1 P04
d 0 1 0 0 P02
我想使用 tidyverse,因为我对它更满意,但无论如何都行
我不会让你做我尝试过的愚蠢尝试......
谢谢!

最佳答案

首先,在你的小标题中添加一个存在/不存在指示器。由于您只有“存在”开始,因此每个值都是 1

df %>% add_column(Present=1)
现在使用 pivot_wider整理你的数据
df %>% 
add_column(Present=1) %>%
pivot_wider(names_from=Symbiont, values_from=Present)
最后,更换 NA我们已经引入了,对应于缺勤,用 0 s。
df %>% 
add_column(Present=1) %>%
pivot_wider(names_from=Symbiont, values_from=Present) %>%
replace(is.na(.), 0)
给予
# A tibble: 6 x 6
Species Location s01 s02 s03 s04
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 a P01 1 0 1 0
2 b P01 0 1 0 0
3 c P02 1 1 1 0
4 a P03 0 0 1 0
5 d P02 0 1 0 0
6 c P04 0 0 0 1

关于r - 在数据框中创建存在/不存在列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63203805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com