本文介绍了用新值替换每个组/因子的第一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我试图用单独的 data.frame 中的新值替换每个 IndID 的第一个值。请注意,每个 IndID 的观察次数不同。 使用下面的示例代码,我想将 number1 和 number2 中的第一个值替换为 dat2 df 。在某些情况下,替换值为 NA 。 set.seed(1) dat 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 [16,2:3] dat [26,2:3]< - c(888,444) dat 解决方案您可以尝试: 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 这篇关于用新值替换每个组/因子的第一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-13 16:19