0
我想要使用邏輯向量'告訴'sapply哪些列在數據集中進行數字化。使用邏輯向量與sapply
在我的數據中有NAs,但所有變量都是數字或字符。我正在做第一個完整的案例(下面的硬代碼,但會愛建議!),並根據字符串中的第一個字符是數字還是字母來創建邏輯向量。我想用這個邏輯向量來告訴sapply哪些列要做數字。
#make data frame, this should return an all 'character' data frame
color <- c("red", "blue", "yellow")
number <- c(NA, 1, 3)
other.number <- c(4, 5, 7)
df <- cbind(color, number, other.number) %>% as.data.frame()
#get the first character of the variables in the first complete case
temp <- sapply(df, function(x) substr(x, 1, 1)) %>% as.data.frame() %>%
.[2,] %>% # hard code, this is the first 'complete case'
gather() %>%
#make the logical variable, which can be used as a vector
mutate(vec= ifelse(value %in% letters, FALSE, TRUE)) # apply this vector to sapply + as.numeric to the df
'df < - data.frame(color,number,other.number)'會猜出你的類型。 – troh
我不會遵循那條路線,而是選擇你離開的地方,'df [temp $ vec] < - lapply(df [temp $ vec],as.numeric)' - 哪個會起作用** IF ** your original變量是字符而不是因素 – Sotos
你真的不需要'data.frame'來保存'logical'向量。嘗試:'isnum < - sapply(df,is.numeric); df [isnum] < - lapply(df [isnum],as.numeric)'。 – r2evans