用另一列 R 替换一列中的值
replacing values in a column with another column R
我有两个不同维度的表,现在我想根据userids将值datA$swl1替换为datB$swl2中的值。
数据A
id swl1
1 0.8
2 0.7
3 0.4
4 0.7
5 0.0
数据B
id swl2
1 0.8
3 0.6
5 0.7
输出
datA(此处swl1被swl2中的新值替换,但并不是所有的id都有新值,没有的id保留原值)
id swl1
1 0.8
2 0.7
3 0.6
4 0.7
5 0.7
怎么做?
您可以使用 merge
匹配 id
,然后在 swl1
列中替换 datB
中存在的项目:
datC <- merge(datA, datB, all.x=TRUE)
datC
## id swl1 swl2
## 1 1 0.8 0.8
## 2 2 0.7 NA
## 3 3 0.4 0.6
## 4 4 0.7 NA
## 5 5 0.0 0.7
这匹配行。现在将 swl1
列中的那些值替换为 swl2
列中的非 NA
值:
datC$swl1 <- ifelse(is.na(datC$swl2), datC$swl1, datC$swl2)
datC$swl2 <- NULL
datC
## id swl1
## 1 1 0.8
## 2 2 0.7
## 3 3 0.6
## 4 4 0.7
## 5 5 0.7
如果你想 select 最大值,不管它在哪一列,你可以尝试
library(dplyr)
datA <- data.frame(id=c(1,2,3,4,5), swl1=c(0.8, 0.7, 0.4, 0.7, 0.0))
datB <- data.frame(id=c(1,3,5), somename=c(0.8, 0.6, 0.7))
datC <- full_join(datA, datB)
datA <- data.frame(id=c(1:5))
datA$swli1 <- apply(datC[, c('swl1', 'somename')], 1, function(x) max(na.omit(x)))
> datA
id swli1
1 1 0.8
2 2 0.7
3 3 0.6
4 4 0.7
5 5 0.7
一行代码即可得到这个结果:
datA$swl1[datA$id %in% datB$id] <- datB$swl2
#> datA
# id swl1
#1 1 0.8
#2 2 0.7
#3 3 0.6
#4 4 0.7
#5 5 0.7
使用 %in%
运算符,我们 select 列 datA$swl1
的条目属于与 datB
中列出的行相同 id
的行. datA$swl1
列中的这些值然后被 datB
的 swl2
列的条目替换。
IIUC,使用 data.table v1.9.5
:
require(data.table)
setDT(datA)[datB, swl1 := swl2, on = "id"]
datA
参考更新。
我有两个不同维度的表,现在我想根据userids将值datA$swl1替换为datB$swl2中的值。
数据A
id swl1
1 0.8
2 0.7
3 0.4
4 0.7
5 0.0
数据B
id swl2
1 0.8
3 0.6
5 0.7
输出
datA(此处swl1被swl2中的新值替换,但并不是所有的id都有新值,没有的id保留原值)
id swl1
1 0.8
2 0.7
3 0.6
4 0.7
5 0.7
怎么做?
您可以使用 merge
匹配 id
,然后在 swl1
列中替换 datB
中存在的项目:
datC <- merge(datA, datB, all.x=TRUE)
datC
## id swl1 swl2
## 1 1 0.8 0.8
## 2 2 0.7 NA
## 3 3 0.4 0.6
## 4 4 0.7 NA
## 5 5 0.0 0.7
这匹配行。现在将 swl1
列中的那些值替换为 swl2
列中的非 NA
值:
datC$swl1 <- ifelse(is.na(datC$swl2), datC$swl1, datC$swl2)
datC$swl2 <- NULL
datC
## id swl1
## 1 1 0.8
## 2 2 0.7
## 3 3 0.6
## 4 4 0.7
## 5 5 0.7
如果你想 select 最大值,不管它在哪一列,你可以尝试
library(dplyr)
datA <- data.frame(id=c(1,2,3,4,5), swl1=c(0.8, 0.7, 0.4, 0.7, 0.0))
datB <- data.frame(id=c(1,3,5), somename=c(0.8, 0.6, 0.7))
datC <- full_join(datA, datB)
datA <- data.frame(id=c(1:5))
datA$swli1 <- apply(datC[, c('swl1', 'somename')], 1, function(x) max(na.omit(x)))
> datA
id swli1
1 1 0.8
2 2 0.7
3 3 0.6
4 4 0.7
5 5 0.7
一行代码即可得到这个结果:
datA$swl1[datA$id %in% datB$id] <- datB$swl2
#> datA
# id swl1
#1 1 0.8
#2 2 0.7
#3 3 0.6
#4 4 0.7
#5 5 0.7
使用 %in%
运算符,我们 select 列 datA$swl1
的条目属于与 datB
中列出的行相同 id
的行. datA$swl1
列中的这些值然后被 datB
的 swl2
列的条目替换。
IIUC,使用 data.table v1.9.5
:
require(data.table)
setDT(datA)[datB, swl1 := swl2, on = "id"]
datA
参考更新。