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