gpt4 book ai didi

r - 结合使用 pivot_longer 和 pivot_wider

转载 作者:行者123 更新时间:2023-12-02 16:05:49 25 4
gpt4 key购买 nike

我有一个在各个列中包含大量 NaN 的数据框。

df <- data.frame(
Data1 = c(3,2,1,NaN, NaN, NaN),
Data2 = c(NaN, NaN, NaN, 3,5,3),
Data3 = c(NaN, NaN, 7,5,1, NaN)
)

我试图通过使用 pivot_longer 来摆脱 NaN 值,filterNaN 上>values 并使用 pivot_wider 将正数重新放回到它们原来的列中,然而,这失败了:

library(tidyr)
df %>%
pivot_longer(c("Data1","Data2","Data3")) %>%
filter(!is.na(value)) %>%
pivot_wider(names_from = name,
values_from = value)
# A tibble: 1 x 3
Data1 Data3 Data2
<list> <list> <list>
1 <dbl [3]> <dbl [3]> <dbl [3]>
Warning message:
Values are not uniquely identified; output will contain list-cols.
* Use `values_fn = list` to suppress this warning.
* Use `values_fn = length` to identify where the duplicates arise
* Use `values_fn = {summary_fun}` to summarise duplicates

代码有什么问题,如何实现这个输出?

  Data1 Data2 Data3
3 3 7
2 5 5
1 3 1

最佳答案

这个特殊问题可以使用 purrr 巧妙地解决:

map_dfr(df, na.omit)

Data1 Data2 Data3
<dbl> <dbl> <dbl>
1 3 3 7
2 2 5 5
3 1 3 1

关于r - 结合使用 pivot_longer 和 pivot_wider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69435246/

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