2017-03-07 6 views
1

私は以下のようなexample_dfを持っています。これには4セットの列があり、各セットに2列あります。基本的には、2つの列のすべてのセットを取得し、その結果の2つの列にデータを移動する簡単な方法が必要です(result_dfの下に表示されています。これを自動化する方法に関するアイデアはありますか?ここで2列ごとに2列の最終セットにする

set.seed(20) 
example_df <- data.frame("test1" = c(rnorm(6), rep(NA, 18)), 
         "test2" = c(rnorm(6), rep(NA, 18)), 
         "test3" = c(rep(NA, 6), rnorm(6), rep(NA, 12)), "test4" = c(rep(NA, 6), rnorm(6), rep(NA, 12)), 
         "test5" = c(rep(NA, 12), rnorm(6), rep(NA, 6)), "test6" = c(rep(NA, 12), rnorm(6), rep(NA, 6)), 
         "test7" = c(rep(NA, 18), rnorm(6)), "test8" = c(rep(NA, 18), rnorm(6))) 

result_df <- data.frame("total1" = c(example_df[c(1:6),1], example_df[c(7:12),3], example_df[c(13:18),5], example_df[c(19:24),7]), 
         "total2" = c(example_df[c(1:6),2], example_df[c(7:12),4], example_df[c(13:18),6], example_df[c(19:24),8])) 
+1

を削除します。コメントとソリューションをありがとう! –

答えて

1

期待される出力を作成するための2つのオプションがあります。

1)我々は、論理インデックスを使用して 'example_df'()の交互の列をサブセット化することによって2列data.frameを作成unlist

total1 <- na.omit(unlist(example_df[c(TRUE, FALSE)])) 
total2 <- na.omit(unlist(example_df[c(FALSE, TRUE)])) 
d1 <- data.frame(total1, total2) 
row.names(d1) <- NULL 

#checking with the OP's output 
all.equal(d1, result_df, check.attributes=FALSE) 
#[1] TRUE 

または単一ステップ

na.omit(do.call(rbind, Map(cbind, example_df[c(TRUE, FALSE)], example_df[c(FALSE, TRUE)]))) 
にNASに削除

2)listの列のシーケンスをループし、サブセット 'example_df'、rbindrbindlistlist要素は、あなたが、正しいです一度くらいまでやってのNA

library(data.table) 
rbindlist(lapply(seq(1, ncol(example_df), by =2), function(i) 
     example_df[i:(i+1)]))[complete.cases(test1, test2)] 
2
odd_cols <- as.logical(1:ncol(example_df) %% 2) 

result_df <- data.frame(total1 = as.vector(apply(example_df[, odd_cols], 2, na.omit)), 
         total2 = as.vector(apply(example_df[,!odd_cols], 2, na.omit))) 
関連する問題