簡體   English   中英

R 迭代 df 中的 1600 列,二進制值為 0 和 1,並從其他兩列復制值以按組保存在數組中

[英]R iterating through 1600 cols in df with binary values 0 and 1 and copy values from two other columns to save in an array by group

我有一個 Dataframe df,基於二進制數據 0 和 1 值,有 1600 列名為 X1,X2,X3....X1600,這些 0 和 1 值在前 2 列中具有相應的緯度和經度數據。 我必須用二進制值一個接一個地遍歷 Dataframe 的每一列。 考慮到第一列,我必須根據 0 和 1 值對其進行分組,並且它們對應的緯度和經度值應復制到二維數組或列表中,以便在稍后階段轉換為矩陣。

使用 for 循環並不理想,是否有任何簡化的方法可以讓這個矩陣 x 和 y 具有 2 列?

我的 df 看起來像這樣:

緯度 經度 X1 X2 X3...
45.65 11.54 0 1 0
62.87 18.17 1 0 0
51.30 1.10 0 0 1

我想在 X1 的基礎上得到的是:

X:

緯度 經度
45.65 11.54
51.30 1.10

是:

緯度 經度
62.87 18.17

我需要對所有 1600 列一一繼續。 任何建議將不勝感激。

正如我在評論中解釋的那樣,我認為這是一個壞主意。 但這里有代碼:

m = as.matrix(df[c("Latitude", "Longitude")])
results = lapply(df[-(1:2)], function(x) 
  list(
    x = m[x == 0, , drop = FALSE], 
    y = m[x == 1, , drop = FALSE]
  )
)
names(results) = names(df)[-(1:2)]

我會如何建議這樣做(未經測試,可能不工作的代碼)

m = as.matrix(df[c("Latitude", "Longitude")])
cols = names(df)[-(1:2)]
results = list()
for(i in seq_along(cols)) {
  pea_result = peacock2(
    x = m[df[[cols[i]]] == 0, ], 
    y = m[df[[cols[i]]] == 1, ],
    ... # other args for peacock
  )
  results[[cols[i]]] = pea_result$pvalue
  ## alternately, you could make each item of results
  ## a sub-list that records more than just the p value
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM