[英]How to replace elemets in second column of data frame if the element in first column match another element in another data.frame?
I want to replace characters in second column of a data.frame if their first column matches in another data.frame. 我想替换data.frame第二列中的字符,如果它们的第一列与另一个data.frame中的字符匹配。 So the files are like this: 所以文件是这样的:
File1: 文件1:
Genotype Group Type
1 08ZB02005DH01 08ZB02005DH01 Line
2 08ZB07005DH04 08ZB07005DH04 Line
3 08ZB08B06DH02 08ZB08B06DH02 Line
4 08ZB13005DH04 08ZB13005DH04 Line
5 08ZB18B24DH01 08ZB18B24DH01 Line
6 JRP4RA6121-002 JRP4RA6121-002 Line
File2: 文件2:
Genotype POL RE ZE
1 08ZB08B06DH02 102.6110 94.94690 97.33455
2 08ZB18B24DH01 102.3411 94.18070 96.29505
3 08ZB02005DH01 101.0357 95.59205 96.62890
4 08ZB13005DH04 101.9972 96.57825 98.62155
5 08ZB07005DH04 103.5134 92.92665 96.10605
This is the code that I use: 这是我使用的代码:
Group_code1 <- 'TS'
Group_code2 <- 'PS'
for (i in 1:dim(file1)[1]) {
if ((match(file1[i,1],file2[,1], nomatch=0)) >= 1) {test[i,2]<-Group_code2} else { test[i,2]<-Group_code2}
}
what I expect as output is: 我期望的输出是:
Genotype Group Type
1 08ZB02005DH01 TS Line
2 08ZB07005DH04 TS Line
3 08ZB08B06DH02 TS Line
4 08ZB13005DH04 TS Line
5 08ZB18B24DH01 TS Line
6 JRP4RA6121-002 PS Line
but I get this error: 但是我得到这个错误:
Warning messages:
1: In `[<-.factor`(`*tmp*`, iseq, value = "PS") :
invalid factor level, NA generated
I would like to keep this part of the code(or at least something similar): 我想保留这部分代码(或至少类似的东西):
Group_code1 <- 'TS'
Group_code2 <- 'PS'
thanks in advance 提前致谢
如果df1
是您的第一个data.frame
而df2
是第二个,则可以尝试:
df1$Group<-c("PS","TS")[ (df1$Group %in% df2$Genotype) +1]
An option using data.table
使用data.table
的选项
library(data.table)
setkey(setDT(df1), Group)[df2[,1, drop=FALSE],
Group:='TS'][Group!='TS', Group:='PS'][]
# Genotype Group Type
#1: 08ZB02005DH01 TS Line
#2: 08ZB07005DH04 TS Line
#3: 08ZB08B06DH02 TS Line
#4: 08ZB13005DH04 TS Line
#5: 08ZB18B24DH01 TS Line
#6: JRP4RA6121-002 PS Line
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.