2017-02-18 62 views
0

我需要將矢量轉換爲數字字符串。我試着在here的解決方案,但我得到一個錯誤信息R將矢量轉換爲數字參考

例如與此數據集:

v1 <- rep(c('a','b'),3) 
v2 <- rep(c('c','d','e'),2) 
vdf <- data.frame(v1, v2) 

sapply(vdf, class) 
     v1  v2 
"factor" "factor" 

sapply(vdf, mode) #I'm not sure why the mode shows as numeric as the value is a charecter 
     v1  v2 
"numeric" "numeric" 

我想改造,使每個專欄中,我引用的每個向量的1,2- ,3,...這樣的:

v1c <- rep(c(1,2),3) 
v2c <- rep(c(1,2,3),2) 
vdfc <- data.frame(v1c, v2c) 

sapply(vdfc, class) 
     v1c  v2c 
"numeric" "numeric" 
    sapply(vdfc, mode) 
     v1c  v2c 
"numeric" "numeric" 

請注意,我有不同數量的載體

的一些列當我嘗試它與迪特Menne的解決方案轉換我得到和錯誤消息:

df$iv1 = as.integer(df$v1) 
df$iv1 = as.integer(as.factor(df$v1)) 

Error in `$<-.data.frame`(`*tmp*`, "iv1", value = integer(0)) : replacement has 0 rows, data has 10 

我做錯了什麼或有沒有更好的方式來轉換數據?

+2

'VDF [] < - lapply(VDF,as.integer)' – Sotos

+0

工程。謝謝Sotos – Selrac

+1

'vdf < - data.frame(v1,v2,stringsAsFactors = FALSE)' –

回答

0

感謝Sotos的評論,我已經能夠輕鬆解決這個問題。按照他的意見,對我工作的解決方案是

VDF [] < - lapply(VDF,as.integer)

這整個數據框轉換一氣呵成。

希望它可以幫助別人