2012-12-05 86 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