2017-03-03 5 views
0

Meine Datensatz smarket (aus der Bibliothek ISLR) eine Spalte Richtung wieGuss String-Spalte in numerische

Direction  
1 Up  
2 Down  
3 Down  
4 Up  
5 Down  
6 Up 

Wie werfe ich es in eine binäre Spalte wie

Direction  
1 0  
2 1  
3 1  
4 0  
5 1  
6 0  

tun folgendes I bekomme nichts. Was soll ich machen?

data <- Smarket 
data$Direction <- as.factor(as.numeric(data$Direction))  

Antwort

1
df1$binary <- as.integer(df1$Direction == 'Down') 
df1 
# Direction binary 
# 1  Up  0 
# 2  Down  1 
# 3  Down  1 
# 4  Up  0 
# 5  Down  1 
# 6  Up  0 

Daten:

df1 <- structure(list(Direction = structure(c(2L, 1L, 1L, 2L, 1L, 2L), 
              .Label = c("Down", "Up"), 
              class = "factor")), 
       .Names = "Direction", class = "data.frame", 
       row.names = c(NA, -6L))