[英]R Question: How do I add data to a column without replacing existing data?
So I have a basic table with empty column 1所以我有一个空列 1 的基本表
df df
ident col1
1 NA
2 NA
3 NA
4 NA
I have two other tables:我还有另外两个表:
df1 df1
ident col1
2 Yes
3 Yes
df2 df2
ident col1
1 No
4 No
I am trying to add data from each df1 and df2 to the first table but when I add the second df2 data it replaces the current entires there that don't match with NA.我试图将每个 df1 和 df2 中的数据添加到第一个表中,但是当我添加第二个 df2 数据时,它会替换那里与 NA 不匹配的当前数据。 So I wan't to add df1 data into col1 and then add df2 data into col1 by matching ident numbers and without replacing values in there.所以我不想将 df1 数据添加到 col1 中,然后通过匹配标识号而不替换其中的值将 df2 数据添加到 col1 中。
Here is my code:这是我的代码:
df$col1<- df1$col1[match(df$ident, df1$ident)]
and then I do the same for df2 but it replaces df1 data...然后我对 df2 做同样的事情,但它取代了 df1 数据......
Any suggestions?有什么建议? Thanks谢谢
PS.附注。 My data is much more complicated than this, I just figured i would boil it down easier for ya.我的数据比这复杂得多,我只是想我会为你更容易地把它归结起来。
You just need to do the match the other way around你只需要反过来做匹配
df$col1[match(df1$ident, df$ident)] <- df1$col1
df$col1[match(df2$ident, df$ident)] <- df2$col1
df
# ident col1
# 1: 1 No
# 2: 2 Yes
# 3: 3 Yes
# 4: 4 No
You can also do this with data.table update joins您也可以使用 data.table 更新连接来做到这一点
library(data.table)
setDT(df)
df[, col1 := as.character(col1)]# may not be necessary (if data is already char)
df[df1, on = .(ident), col1 := i.col1]
df[df2, on = .(ident), col1 := i.col1]
df
# ident col1
# 1: 1 No
# 2: 2 Yes
# 3: 3 Yes
# 4: 4 No
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.