簡體   English   中英

當我遍歷行並有條件地更改一列時,該循環的執行速度非常慢。 如何使操作更快?

[英]When I loop through rows and conditionally change one column, the loop executes really slowly. How can I make the operation faster?

在這里,我正在檢查每一行中的第一列元素是否等於“ 060075”。 如果沒有,我想將元素更改為“其他”。 當我在前100行上運行代碼時,它需要10秒鍾。 我需要在650萬行上運行它。 我怎樣才能使其更快?

for (i in 1:nrow(full_data_2)){
    if (full_data_2[i, 1] != "06075") {
      full_data_2[i, 1] <- "Other"
    }
  }

這是str(full_data_2)

data.frame':    6497651 obs. of  6 variables:
 $ fips     : chr  "Other" "Other" "Other" "Other" ...
 $ SCC      : chr  "10100401" "10100404" "10100501" "10200401" ...
 $ Pollutant: chr  "PM25-PRI" "PM25-PRI" "PM25-PRI" "PM25-PRI" ...
 $ Emissions: num  15.714 234.178 0.128 2.036 0.388 ...
 $ type     : chr  "POINT" "POINT" "POINT" "POINT" ...
 $ year     : int  1999 1999 1999 1999 1999 1999 1999 1999 1999 1999 ..

您需要利用向量運算來加快處理速度。 在元素上操作有時需要復制數據框。 更改代碼的最簡單方法是

full_data_2[,1] <- ifelse(full_data_2[,1]=="06075", "Other", full_data_2[,1])

data.table是另一個在列表上運行的替代方法,通常比數據幀更快。

看看是否可行

# assume df is your data frame
library(data.table)
setDT(df) # convert df to data table
setkey(df, col_1) # key the column of interest. Assume it's col_1
df["06075", col_1 := "Other"]  # Assign "Other" to col_1 if element is "06075"
df

暫無
暫無

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

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