gpt4 book ai didi

r - 如何整齐地组合稀疏列

转载 作者:行者123 更新时间:2023-12-01 07:52:19 27 4
gpt4 key购买 nike

一位同事有一些由许多稀疏列组成的数据,这些列应该折叠成几个填充的列。例如:

d1 <- data.frame(X1 = c(rep("Northampton", times=3), rep(NA, times=7)), 
X2 = c(rep(NA, times=3), rep("Amherst", times=5), rep(NA, times=2)),
X3 = c(rep(NA, times=8), rep("Hadley", times=2)),
X4 = c(rep("Stop and Shop", times=2), rep(NA, times=6), rep("Stop and Shop", times=2)),
X5 = c(rep(NA, times=2), rep("Whole Foods", times=6), rep(NA, times=2)))

d1
X1 X2 X3 X4 X5
1 Northampton <NA> <NA> Stop and Shop <NA>
2 Northampton <NA> <NA> Stop and Shop <NA>
3 Northampton <NA> <NA> <NA> Whole Foods
4 <NA> Amherst <NA> <NA> Whole Foods
5 <NA> Amherst <NA> <NA> Whole Foods
6 <NA> Amherst <NA> <NA> Whole Foods
7 <NA> Amherst <NA> <NA> Whole Foods
8 <NA> Amherst <NA> <NA> Whole Foods
9 <NA> <NA> Hadley Stop and Shop <NA>
10 <NA> <NA> Hadley Stop and Shop <NA>
X1:X3应该折叠成一列名为 Town 和 X4:X5到名为 Store 的一列中。这里一定有一个tidyverse解决方案。我试过 gather()unite()但没有发现任何优雅的东西。

最佳答案

您可以使用 coalesce :

d1 %>% mutate_if(is.factor, as.character) %>%    # coerce explicitly
transmute(town = coalesce(X1, X2, X3),
store = coalesce(X4, X5))

## town store
## 1 Northampton Stop and Shop
## 2 Northampton Stop and Shop
## 3 Northampton Whole Foods
## 4 Amherst Whole Foods
## 5 Amherst Whole Foods
## 6 Amherst Whole Foods
## 7 Amherst Whole Foods
## 8 Amherst Whole Foods
## 9 Hadley Stop and Shop
## 10 Hadley Stop and Shop

关于r - 如何整齐地组合稀疏列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43401392/

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