2017-06-16 6 views
0

私は64個のデータフレームを持つリストを持っています。 Dataframe 1とDataframe 5は同じ行名を持つ必要があります。 2および6,3,7などと同じです。 私はforループを実行して新しいリストを作成できますが、何かがうまくいきません。それを再現するためにここでリストに格納されたデータフレームの行をフィルタリングし、新しいリストを作成する

簡単な例:

# Create dataframes and store in list 
dfA <- data.frame(v1=c(1:6), v2=c("x1","x2","x3","x4","x5","x6")) 
dfB <- data.frame(v1=c(1:6), v2=c("x1","x2","x3","x4","x5","x6")) 
dfC <- data.frame(v1=c(1:5), v2=c("x1","x2","x3","x4","x5")) 
dfD <- data.frame(v1=c(1:4), v2=c("x1","x2","x3","x4")) 
example_dataframes = list(dfA, dfB, dfC, dfD) 

# These vectors give the order of the process 
vectorA = c(1,2) 
vectorB = c(3,4) 

# Create new list and start for loop 
filtered_dataframes = list() 
for (i in vectorA) { 
    for (j in vectorB) { 
df1 = example_dataframes[[i]] 
df2 = example_dataframes[[j]] 
test = intersect(df1$v2, df2$v2) 
filtered_dataframes[[i]] <- df1[which(df1$v2 %in% test),] 
filtered_dataframes[[j]] <- df2[which(df2$v2 %in% test),] 
} 
} 

この例では、私が得ることを期待:

sapply(filtered_dataframes, nrow) 
> 5 4 5 4 
+0

2層の再帰的なサイクルではなく、vectorAとvectorBのインデックスをトラバースするために1つのfor-cycleだけが必要です。 – mt1022

答えて

0

この修正版は、あなたが必要な結果を得るために動作するはずです。

dfA <- data.frame(v1=c(1:6), v2=c("x1","x2","x3","x4","x5","x6")) 
dfB <- data.frame(v1=c(1:6), v2=c("x1","x2","x3","x4","x5","x6")) 
dfC <- data.frame(v1=c(1:5), v2=c("x1","x2","x3","x4","x5")) 
dfD <- data.frame(v1=c(1:4), v2=c("x1","x2","x3","x4")) 
example_dataframes = list(dfA, dfB, dfC, dfD) 

# Put the comparison vectors into a list. Exampl: To compare dataframes 1 and 3, put in c(1,3) 
vector.list <- list(c(1,3),c(2,4)) 

# Create new list and start for loop 
filtered_dataframes = list() 

# Loop through the list of vectors 
for (i in vector.list) { 
    # Get the first dataframe from the current vector being processed 
    df1 = example_dataframes[[i[1]]] 

    # Get the second dataframe from the current vector being processed 
    df2 = example_dataframes[[i[2]]] 

    # Get the intersection of the two dataframes 
    test = intersect(df1$v2, df2$v2) 

    # Add the first filtered dataframe to the list of filtered dataframes 
    filtered_dataframes[[i[1]]] <- df1[which(df1$v2 %in% test),] 

    # Add the second filtered dataframe to the list of filtered dataframes 
    filtered_dataframes[[i[2]]] <- df2[which(df2$v2 %in% test),] 
    } 
+0

ありがとうございますが、私は期待したものを手に入れません。新しいリストでは、dfAとdfCはnrow = 5であり、dfBとdfDはnrow = 4でなければなりません。私は同じ順序でそれらを保ちたいと思います。 – fibar

+0

あなたが見ている問題を解決するために私の答えを修正しました。 'vector.list'で比較するデータフレームを設定すると、同じベクトルに2つのデータフレームインデックスを割り当てます。IE' c(1,3) 'は、インデックス1と3のデータフレームを' example.dataframes'リストから比較します。データフレームが 'filtered_dataframes'リストに出力されるとき、元のインデックス位置にとどまるようにデータフレームを変更しました。 –

関連する問題