2012-12-05 83 views
0

对不起打扰你。我有一个包含类似项data.frame:用数字替换字符

F1008Y
F1008Y
406_407insD
R1207 *

我想用 “1” 替换所有的项目。 这可以怎么做?

+0

嗨。我的意思是我想让“F1008Y”变成1. – Bfu38

回答

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 
+0

嗨Jiber,非常感谢。我忘记写我的问题data.frame也包含“0”项目。所以当我运行你的代码时,“0”也被替换掉了。相反,他们必须保持0. – Bfu38

+0

@ Bfu38看到我的编辑 –

+0

好吧,非常感谢你! – Bfu38

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