我试图用单独的 data.frame 中的新值替换每个 IndID 的第一个值。请注意,每个 IndID 的观察次数不同。
使用下面的示例代码,我想将 number1 和 number2 中的第一个值替换为 dat2 df 。在某些情况下,替换值为 NA 。
set.seed(1) dat < - data.frame(IndID = rep(c ,A,B,c,c,D),每个= 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 ]您可以尝试:
dat [match(dat2 $ IndID,dat $ IndID),]< - dat2 / pre>I am trying to replace the first values of each IndID with new values from a separate data.frame. Note, there are a differing number of observations for each IndID.
Using the example code below, I want to replace the first values of number1 and number2 with the corresponding column names in the dat2 df. In some instances, the replacement value is 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))The preferred result would produce the following with a much more effective and elegant approach. I suspect dplyr is an appropriate tool, but always enjoy learning other methods.
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解决方案
You could try:
dat[match(dat2$IndID, dat$IndID),] <- dat2
更多推荐
用新值替换每个组/因子的第一个数字
发布评论