很抱歉打扰你。我有一个 data.frame 包含以下项目:
F1008Y
F1008Y
406_407insD
R1207*
我想用“1”替换所有这些项目。如何做到这一点?
您可以使用ifelse
DF <- read.table(text="F1008Y
F1008Y
406_407insD
R1207*
0
0", header=FALSE) # adding some 0
DF # this is your data.frame
V1
1 F1008Y
2 F1008Y
3 406_407insD
4 R1207*
5 0
6 0
ifelse({df <- DF; df!=0}, df[,] <- 1, df[,] <- 0) # replacing
V1
[1,] 1
[2,] 1
[3,] 1
[4,] 1
[5,] 0
[6,] 0
# the original data.frame remains the same
DF
V1
1 F1008Y
2 F1008Y
3 406_407insD
4 R1207*
5 0
6 0
这是一个利用以下事实的示例:当您as.numeric
在将数字和字符串混合在一起的向量上使用时,字符串会转换为NA
. 我添加了一个额外的专栏只是为了好玩。
DF <- read.table(text="F1008Y
F1008Y
406_407insD
R1207*
0
0", header=FALSE)
DF$V2 <- DF$V1
DF.bak <- DF ## Backups are always nice
DF
# V1 V2
# 1 F1008Y F1008Y
# 2 F1008Y F1008Y
# 3 406_407insD 406_407insD
# 4 R1207* R1207*
# 5 0 0
# 6 0 0
## By default, the columns have been read in as factors. Convert to character
DF[sapply(DF, is.factor)] = lapply(DF[sapply(DF, is.factor)], as.character)
DF[is.na(sapply(DF, as.numeric))] <- 1
# Warning messages:
# 1: In lapply(X = X, FUN = FUN, ...) : NAs introduced by coercion
# 2: In lapply(X = X, FUN = FUN, ...) : NAs introduced by coercion
DF
# V1 V2
# 1 1 1
# 2 1 1
# 3 1 1
# 4 1 1
# 5 0 0
# 6 0 0