只是一个简单的问题:如果这些值存在于所有数据框的列中,我如何用其他值替换这些值? mapvalues
和 recode
等函数仅在指定列时才有效,但在我的例子中,数据框有 89 列,因此会很耗时。
为清楚起见,请考虑以下示例。我想用另一个值替换 [NULL]。
例子:
a <- c("NULL",2,"NULL")
b <- c(3, "NULL", 1)
df <- data.frame(a, b)
df
a b
0 NULL 3
1 2 NULL
2 NULL 1
示例和我的案例不同的是,数据集是[35383 x 89],而我要替换的值不止一个。
提前感谢您的宝贵时间。
最佳答案
Ronak Shah 评论的扩展。如果您愿意,可以添加 0。或者,如果您愿意,可以将其替换为所需的值。
例如,将 NULL 替换为相应列的平均值:
#Run a loop to convert the characters into numbers because for your case it is all characters
#This will change the NULL to NAs.
for (i in colnames(df)){
df[,i] <- as.numeric(df[,i])
}
#Now replace the NAs with the mean of the column
for (i in colnames(df)){
df[,i][is.na(df[,i])] <- mean(df[,i], na.rm=TRUE)
}
您也可以类似地对中位数执行此操作。如果您有任何疑问,请在评论中告诉我。
关于r - 如何替换 r 中所有列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68952699/