我手頭有一個資料集,其中某些問題的答案取決于之前提出的其他問題,并且需要在考慮這些問題的情況下執行聚合(例如:“difficultyX”需要“isdifficult”== 1,我必須計算 is.na (difficultyX) 知道條件成立)
問題是我有幾列都有不同的條件要滿足(X1 必須檢查 Y1 列,x2 列 Y2 等......)
現在我已經嘗試旋轉表并將對應關系加入到條件列和值中,我的資料庫看起來像這樣:
after pivoting and joining
test<-tibble(Y1=1:3,Y2=1:3,var_to_test=c("x1","x2","x3"),condition=c("Y1","Y2","Y2"),value=c(1,2,2))
and I want the output to lok like this :
testoutput<-tibble(Y1=1:3,Y2=1:3,var_to_test=c("x1","x2","x3"),condition=c("Y1","Y2","Y2"),value=c(1,2,1),cond_verif=c(T,T,F))
現在我可以對一行執行我想要的測驗
#this works
test[[1,test$condition[1]]]==test$value[1]
#this does not
test[[,test$condition]]==test$value
#this one takes awfully long (2 secs for 10K obs, in long format I have 700K of them)
for(i in 1:3){
vec[i]<-test[[i,test$condition[i]]]==test$value[i]
}
因此,我正在尋找一種可以在合理的時間內作業的概括,它可以與 map 函式、apply 函式、dplyr 甚至 base R 一起使用,但我還沒有弄清楚......
感謝您的時間
uj5u.com熱心網友回復:
library(dplyr)
library(tidyr)
test<-tibble(Y1=1:3,Y2=1:3,var_to_test=c("x1","x2","x3"),condition=c("Y1","Y2","Y2"),value=c(1,2,2))
可能的解決方案tidyr::pivot_longer:
1. 以長格式提供資料,其中有一列指定每個測驗的(預期?)值。
2.過濾掉未使用的行(test_condition與應用的測驗不匹配的行)
3.比較值并創建新列 cond_verif
test %>%
pivot_longer(col = c(Y1, Y2), names_to = "test_condition", values_to = "test_value") %>%
filter(condition == test_condition) %>%
mutate(cond_verif = value == test_value)
這將回傳:
# A tibble: 3 x 6
var_to_test condition value test_condition test_value cond_verif
<chr> <chr> <dbl> <chr> <int> <lgl>
1 x1 Y1 1 Y1 1 TRUE
2 x2 Y2 2 Y2 2 TRUE
3 x3 Y2 2 Y2 3 FALSE
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465438.html
