我試圖用單獨的data.frame
中的新值替換每個IndID
的第一個值。請注意,每個IndID
都有不同的觀察值。用新值替換每個組的第一個數/因子
使用下面的示例代碼,我想將number1
和number2
的第一個值替換爲dat2
df
中的相應列名稱。在某些情況下,重置值爲NA
。
set.seed(1)
dat <- data.frame(IndID = rep(c("A","A","B","c","c","D"), each = 5),
number1 = sample(1:100,30),
number2 = sample(1:100,30))
dat2 <- data.frame(IndID = c("A","B","c","D"),
number1 = c(555,666,NA,888),
number2 = c(111,222,NA,444))
首選的結果將產生以下更有效和優雅的方法。我懷疑dplyr
是一個合適的工具,但總是喜歡學習其他方法。
dat[1,2:3] <- c(555,111)
dat[11,2:3] <- c(666,222)
dat[16,2:3] <- c(NA,NA)
dat[26,2:3] <- c(888,444)
dat
哇。非常感激。我當然在關注的路線上...... –