我想在第3-9列中将“U”更改为“N”,并将“H”更改为同一行的“type”列的字符。例如,第一行中的“H”将变为“M”,依此类推。我非常感谢R脚本的任何帮助。谢谢。 XW
ID type A01 A02 A03 A04 A05 A06 A07
ss001 M C A U A A H A
ss002 R A H A A A G A
ss003 R H A G A A A U
ss004 R A U A A A A A
ss005 Y C C H T T C C
ss006 Y C T U C C C H
ss007 R A G A H G U G
ss008 K G U T G T H G
ss009 Y T H C T T U C
ss010 K T G T H G T T
答案 0 :(得分:0)
您可以在数据行调用apply
时执行此操作:
# Read in data frame with data stored as characters
df = read.table(text="ID type A01 A02 A03 A04 A05 A06 A07
ss001 M C A U A A H A
ss002 R A H A A A G A
ss003 R H A G A A A U
ss004 R A U A A A A A
ss005 Y C C H T T C C
ss006 Y C T U C C C H
ss007 R A G A H G U G
ss008 K G U T G T H G
ss009 Y T H C T T U C
ss010 K T G T H G T T", header=T, stringsAsFactors=F)
# Manipulate rows
df.mod = as.data.frame(t(apply(df, 1, function(x) {
to.modify <- x[c(-1, -2)]
to.modify[to.modify == "U"] <- "N"
to.modify[to.modify == "H"] <- x[2]
return(c(x[1:2], to.modify))
})))
names(df.mod) <- names(df)
df.mod
# ID type A01 A02 A03 A04 A05 A06 A07
# 1 ss001 M C A N A A M A
# 2 ss002 R A R A A A G A
# 3 ss003 R R A G A A A N
# 4 ss004 R A N A A A A A
# 5 ss005 Y C C Y T T C C
# 6 ss006 Y C T N C C C Y
# 7 ss007 R A G A R G N G
# 8 ss008 K G N T G T K G
# 9 ss009 Y T Y C T T N C
# 10 ss010 K T G T K G T T
答案 1 :(得分:0)
这应该是一种非常有效的方法:
M <- as.matrix(df[-c(1, 2)]) ## Faster to work on a matrix
M[M == "U"] <- "N" ## Replace "U" with "N"
H <- which(M == "H", arr.ind=TRUE) ## Identify the Hs
M[H] <- df[cbind(H[, "row"], 2)] ## Replace with values from "type"
cbind(df[1:2], M) ## Combine
# ID type A01 A02 A03 A04 A05 A06 A07
# 1 ss001 M C A N A A M A
# 2 ss002 R A R A A A G A
# 3 ss003 R R A G A A A N
# 4 ss004 R A N A A A A A
# 5 ss005 Y C C Y T T C C
# 6 ss006 Y C T N C C C Y
# 7 ss007 R A G A R G N G
# 8 ss008 K G N T G T K G
# 9 ss009 Y T Y C T T N C
# 10 ss010 K T G T K G T T