dplyrとの結合の結果として次のデータフレームがあります。
data_frame(id=1:4, a.x = c(1, NA, 3, 4), a.y = c(1, 2, 3, 4), b.x = c(NA, NA, 3, NA), b.y = c(2, 2, NA, 4))
# A tibble: 4 x 5
id a.x a.y b.x b.y
<int> <dbl> <dbl> <dbl> <dbl>
1 1 1 1 NA 2
2 2 NA 2 NA 2
3 3 3 3 3 NA
4 4 4 4 NA 4
そして、で終わる列のすべてのNAを、で終わる列.x
の値に置き換えたいと思います.y
。最終的に、私はこれを達成したいと思います:
# A tibble: 4 x 5
id a.x a.y b.x b.y
<int> <dbl> <dbl> <dbl> <dbl>
1 1 1 1 2 2
2 2 2 2 2 2
3 3 3 3 3 NA
4 4 4 4 4 4
私は次のようなpurrrで試しました:
data_frame(id=1:4, a.x = c(1, NA, 3, 4), a.y = c(1, 2, 3, 4), b.x = c(NA, NA, 3, NA), b.y = c(2, 2, NA, 4)) %>%
map2_dfr(.x = ends_with('.y'), .y = ends_with('.x'), ~ case_when(is.na(.x) ~ .y,
TRUE ~ .x))
どちらが間違っています。ドキュメントは私には少し混乱しています。ここでの問題は、.xがベクトルを予期していることだと思いますが、列のリストを渡すにはどうすればよいですか?
tidyrのソリューション。私たちすることができgather
、列、separate
によって.
、arrange
列によって、fill
アップに向けて、値unite
の列、そして最終的にspread
元の構造にデータフレーム。
library(tidyverse)
dat2 <- dat %>%
gather(Column, Value, -id) %>%
separate(Column, into = c("Col1", "Col2")) %>%
arrange(id, Col1, Col2) %>%
group_by(id, Col1) %>%
fill(Value, .direction = "up") %>%
unite(Column, Col1, Col2, sep = ".") %>%
spread(Column, Value) %>%
ungroup()
dat2
## A tibble: 4 x 5
# id a.x a.y b.x b.y
# * <int> <dbl> <dbl> <dbl> <dbl>
# 1 1 1.00 1.00 2.00 2.00
# 2 2 2.00 2.00 2.00 2.00
# 3 3 3.00 3.00 3.00 NA
# 4 4 4.00 4.00 4.00 4.00
または、データフレーム内の列の順序が適切な場合はtranspose
、data.tableパッケージの関数を使用できますが、処理後に列タイプが変更される可能性があることに注意してください。
dat2 <- dat %>%
data.table::transpose() %>%
fill(everything(), .direction = 'up') %>%
data.table::transpose() %>%
setNames(names(dat))
dat2
# id a.x a.y b.x b.y
# 1 1 1 1 2 2
# 2 2 2 2 2 2
# 3 3 3 3 3 NA
# 4 4 4 4 4 4
または、purrrを使用して、最初に列名がends_with
「x」と「y」のサブセットを作成し、次に元の列の末尾を「x」に置き換えるソリューション。
dat_x <- dat %>% select(ends_with("x"))
dat_y <- dat %>% select(ends_with("y"))
dat[, grepl("x$", names(dat))] <- map2(dat_x, dat_y, ~ifelse(is.na(.x), .y, .x))
dat
# # A tibble: 4 x 5
# id a.x a.y b.x b.y
# <int> <dbl> <dbl> <dbl> <dbl>
# 1 1 1.00 1.00 2.00 2.00
# 2 2 2.00 2.00 2.00 2.00
# 3 3 3.00 3.00 3.00 NA
# 4 4 4.00 4.00 4.00 4.00
データ
dat <- data_frame(id=1:4, a.x = c(1, NA, 3, 4), a.y = c(1, 2, 3, 4), b.x = c(NA, NA, 3, NA), b.y = c(2, 2, NA, 4))
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加