我有兩個不同維度的資料框;資料框 a 和資料框 b。我想用存盤在資料幀 b 中的欄位值替換資料幀 a 中的特定欄位。我找到了一種方法來過濾資料幀 b 的值,我想用它來替換資料幀 a 的欄位。但是,我不知道如何使用條件來索引資料框的特定欄位以替換那里的值......有什么建議嗎?
df_a <- base::cbind(base::as.data.frame(
base::matrix(c(3, 5, 6, 1, 23, 6, 7, 58, 9), ncol = 3)),
c('bli', 'bla', 'blub'))
# create dataframe a
base::colnames(df_a) <- c('col1', 'col2', 'col3', 'col4')
# set colnames of dataframe a
df_b <- base::as.data.frame(base::matrix(base::seq(1, 27, 3), ncol = 3, byrow = TRUE))
# create dataframe b
repl_val <- df_b[2, 2]
# replace value for dataframe a
spc_col1_val <- 5
# row to index dataframe a: column <col1> should have the value <5>
spc_col <- base::paste0('col', '1')
# column to index dataframe a: the specific column is combined out of different variables e.g. <col> and <3>
df_a[df_a$col1 == spc_col1_val, df_a$spc_col] <- repl_val
# THIS DOES NOT WORK
uj5u.com熱心網友回復:
由于看起來您對 R 比較陌生,我將嘗試給出一個完整的答案:我強烈建議不要base::在任何地方使用,原因有兩個:1) 沒有人會卸載base包裹 b) 它看起來很糟糕. 我想我理解您的意圖,并且您會同意我們應該努力使代碼盡可能干凈易讀(以查找/避免錯誤)但是這種風格選擇使它變得更加冗長而沒有任何好處......事實上,它使代碼更難閱讀和理解(正如評論者已經指出在這幾行代碼中存在多個錯誤。并且示例中
仍然存在錯誤(即沒有名為“spc_val_col1”的變數(您將其命名為“spc_col1_val”) ") ) 使用更簡潔的風格有很大幫助!!
現在,如果您關心顯性,創建 df_a 的更簡潔的方法是:
df_a <- data.frame(col1 = c(3, 5, 6),
col2 = c(1, 23, 6),
col3 = c(7, 58, 9),
col4 = c('bli', 'bla', 'blub'))
優點:應有盡有,包括列名,無需進一步操作 df,引入錯誤的方法更少......
對于您使用的第二個作業seq,matrix這可能很有用。雖然我在這里不認為需要它(再次,顯式比隱式更好)但as.data.frame這里不需要,只有 diff 是名稱(無論如何都不使用)
df_b <- data.frame(matrix(seq(1, 27, 3), ncol = 3, byrow = TRUE))
repl_val <- df_b[2, 2] # replace value for dataframe a
spc_col1_val <- 5 # row to index dataframe a: column <col1> should have the value <5>
在您撰寫的注釋中,由不同的變陣列合而成,例如 < col> 和 <3>但隨后您使用了paste0('col', '1') 我希望您能看到這有點令人困惑(再次,如果我們關心關于清晰度,讓所有這些東西都正確實際上會有所幫助......)
spc_col <- paste0('col', '1') # column to index dataframe a: the specific column is combined out of different variables e.g. <col> and <3>
df_a分配前:
col1 col2 col3 col4
1 3 1 7 bli
2 5 23 58 bla
3 6 6 9 blub
下一行有多個錯誤,但最重要的是:我們可以which用來檢索滿足條件的元素的索引,并且我們將列名直接指定為字串,我建議查看?Extract它在 R 中的一個非常重要的函式!
df_a[which(df_a$col1 == spc_col1_val), spc_col] <- repl_val
df_a 賦值后:
col1 col2 col3 col4
1 3 1 7 bli
2 13 23 58 bla
3 6 6 9 blub
請不要將批評視為敵意。我認為您的意圖是正確的,并且顯然愿意投入作業。但我強烈建議專注于真正有用和重要的東西;) 希望這對你有所幫助!
And as a final note: It would be great if you also included an example of the desired output (I assume what I showed is what you wanted but an example of the output would remove all ambiguity (agian, explicit is better ;)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/320751.html
