用数字替换字符

时间:2012-12-05 10:31:22

标签: r

抱歉打扰你。我有一个data.frame,其中包含以下项目:

  

F1008Y
  F1008Y
  406_407insD
  R1207 *

我想用" 1"替换所有项目。 如何做到这一点?

2 个答案:

答案 0 :(得分:3)

您可以使用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

答案 1 :(得分:1)

这是一个利用这样一个事实的例子:当你在一个数字和字符串混合在一起的向量上使用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