我一直在嘗試對資料集 (A2) 的行進行排序以匹配另一個資料集 (A1) 的多列。我曾經使用過一個代碼,它作業得很好。今天我修改了代碼以在新資料集上使用,我得到了不應該得到的 NA。
這是我正在使用的代碼
A4 <- A2[match(paste(A1$Subject,A1$Condition,A1$test, A1$Replication), paste(A2$Subject,A2$Condition,A2$test,A2$Replication)),]
資料:
A1 <- structure(list(Subject = c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2,
2, 2, 2, 2), Condition = c(1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2,
1, 1, 2, 2), test = c(1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2,
2, 2, 2), Replication = c(101, 108, 103, 105, 101, 108, 103,
105, 101, 108, 103, 105, 101, 108, 103, 105), Movement = c(43,
56, 45, 43, 35, 34, 34, 3, 4, 67, 45, 34, 65, 34, 345, 23)), row.names = c(NA,
-16L), class = c("tbl_df", "tbl", "data.frame"))
A2 <-structure(list(Subject = c(2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1,
1, 1, 1, 1, 1), Condition = c(1, 1, 2, 2, 1, 1, 2, 2, 1, 1,
2, 2, 2, 1, 1, 2), test = c(1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1,
1, 2, 2, 2, 2), Replication = c(108, 101, 103, 105, 101, 108,
103, 105, 108, 101, 103, 105, 101, 108, 103, 105), Movement = c(43,
56, 45, 43, 35, 34, 34, 3, 4, 67, 45, 34, 65, 34, 345, 23)), row.names = c(NA,
-16L), class = c("tbl_df", "tbl", "data.frame"))
uj5u.com熱心網友回復:
我們可能會slice在dplyr
library(dplyr)
library(purrr)
library(stringr)
A2 %>%
slice(match(invoke(str_c, across(Subject:Replication, ~
A1[[cur_column()]])), invoke(str_c, across(Subject:Replication))))
-輸出
# A tibble: 14 × 5
Subject Condition test Replication Movement
<dbl> <dbl> <dbl> <dbl> <dbl>
1 1 1 1 101 67
2 1 1 1 108 4
3 1 2 1 103 45
4 1 2 1 105 34
5 1 1 2 108 34
6 1 2 2 105 23
7 2 1 1 101 56
8 2 1 1 108 43
9 2 2 1 103 45
10 2 2 1 105 43
11 2 1 2 101 35
12 2 1 2 108 34
13 2 2 2 103 34
14 2 2 2 105 3
uj5u.com熱心網友回復:
你可以使用一個 merge
join_vars <- c('Subject', 'Condition', 'test', 'Replication')
merge(A2, A1[, join_vars], by = join_vars, all.x = FALSE)
#> Subject Condition test Replication Movement
#> 1 1 1 1 101 67
#> 2 1 1 1 108 4
#> 3 1 1 2 108 34
#> 4 1 2 1 103 45
#> 5 1 2 1 105 34
#> 6 1 2 2 105 23
#> 7 2 1 1 101 56
#> 8 2 1 1 108 43
#> 9 2 1 2 101 35
#> 10 2 1 2 108 34
#> 11 2 2 1 103 45
#> 12 2 2 1 105 43
#> 13 2 2 2 103 34
#> 14 2 2 2 105 3
由reprex 包(v2.0.1)于 2021 年 10 月 17 日創建
uj5u.com熱心網友回復:
您可以使用na.omit,也Reduce讓生活更輕松。
A2[na.omit(match(Reduce(paste, A1[-5]), Reduce(paste, A2[-5]))), ]
# Subject Condition test Replication Movement
# 10 1 1 1 101 67
# 9 1 1 1 108 4
# 11 1 2 1 103 45
# 12 1 2 1 105 34
# 14 1 1 2 108 34
# 16 1 2 2 105 23
# 2 2 1 1 101 56
# 1 2 1 1 108 43
# 3 2 2 1 103 45
# 4 2 2 1 105 43
# 5 2 1 2 101 35
# 6 2 1 2 108 34
# 7 2 2 2 103 34
# 8 2 2 2 105 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/324616.html
下一篇:當我只有值時如何回傳散列中的鍵?
