2017-06-12 56 views
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 
+0

'df < - data.frame(color,number,other.number)'会猜出你的类型。 – troh

+0

我不会遵循那条路线,而是选择你离开的地方,'df [temp $ vec] < - lapply(df [temp $ vec],as.numeric)' - 哪个会起作用** IF ** your original变量是字符而不是因素 – Sotos

+0

你真的不需要'data.frame'来保存'logical'向量。尝试:'isnum < - sapply(df,is.numeric); df [isnum] < - lapply(df [isnum],as.numeric)'。 – r2evans

回答

0

这是一个奇怪的情况,但如果你需要根据自己的第一个元素的数字列转换,那么一个想法是将其转换为数字。由于任何不是数字的元素将返回NA(如警告状态),因此您可以使用该元素进行索引。例如,

ind <- sapply(na.omit(df), function(i) !is.na(as.numeric(i[1]))) 

警告消息: 在FUN(X [[I]],...):受到胁迫

ind 
#  color  number other.number 
#  FALSE   TRUE   TRUE 

df[ind] <- lapply(df[ind], as.numeric) 

str(df) 
#'data.frame': 3 obs. of 3 variables: 
# $ color  : chr "red" "blue" "yellow" 
# $ number  : num NA 1 3 
# $ other.number: num 4 5 7 

DATA

引入的NA
dput(df) 
structure(list(color = c("red", "blue", "yellow"), number = c(NA, 
"1", "3"), other.number = c("4", "5", "7")), .Names = c("color", 
"number", "other.number"), row.names = c(NA, -3L), class = "data.frame") 
+1

这是完美的,谢谢! – RoseS