![](/img/trans.png)
[英]How to convert factor to numeric in R without NAs introduced by coercion warning message
[英]R - convert dataframe columns to numeric - NAs introduced by coercion error
我正在嘗試從這里執行代碼:
在具有 140 列的 dataframe 中
cols = c(1:140);
merged_dataset[,cols] = apply(merged_dataset[,cols], 2, function(x) as.numeric(as.character(x)));
問題在於我得到 NA 的某些列。 有沒有辦法以某種方式從代碼中排除這些列,以便我保留數據並且它們不會轉換為 NA? 如果有幫助,我看到這些列的類型是字符。
如果您已經知道要刪除的列的索引,那么您可以對數據框進行子集化以僅針對某些列:
cols <- c(1:140) # all columns
cols.skip <- c(1,3,5,21) # columns which CAN'T be converted to numeric
cols.keep <- cols[!cols %in% cols.skip]
merged_dataset[,cols.keep] <- apply(merged_dataset[,cols.keep], 2, function(x) {
as.numeric(as.character(x))
})
要使用列名而不是索引來實現類似的邏輯:
cols.skip <- c("a", "b", "c")
cols.keep <- !(names(merged_dataset) %in% cols.skip)
merged_dataset[,cols.keep] <- apply(merged_dataset[,cols.keep], 2, function(x) {
as.numeric(as.character(x))
})
也可以在因子級別內替換任何不正確的字符以更好地提取任何數字:
convert_factors_to_numeric <- function(df) {
as.data.frame(lapply(df,
function(x) {
if (is.factor(x)) {
as.numeric(as.character(trimws(x),
which = "both"))
} else{
x
}
}
),
stringsAsFactors = FALSE)
}
df_converted <- convert_factors_to_numeric(df)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.