用新值替换每个组/因子的第一个数字

编程入门 行业动态 更新时间:2024-10-23 16:14:27
本文介绍了用新值替换每个组/因子的第一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图用单独的 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

更多推荐

用新值替换每个组/因子的第一个数字

本文发布于:2023-10-27 18:53:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534246.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:因子   数字   用新值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!