2017-06-12 57 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