很抱歉这是我第一次发帖,但我有一个关于更换NA值的问题。该作业声明我必须将"A"
的所有值替换为0
所以我尝试了这个命令:
test1[test1 == "A"] <- 0
但它所做的只是生成NA
个值。我尝试使用另一个命令将这些NA
值转换为0
test1[is.na(test1)] <- 0
但我收到"invalid factor level, NA generated"
警告。任何帮助将不胜感激。
答案 0 :(得分:0)
你的意思是
test1 <- c("A","B","C","A","C")
test1 <- replace(test1, test1=="A", 0)
test1
打印
> test1
[1] "0" "B" "C" "0" "C"
表示数据框:
> test2 <- data.frame(col1 = c("A","B","A"),
+ col2 = c("D","B","A"),
+ col3 = c("A","A","X"))
> apply(test2, 1, function(x) {replace(x, x=="A", 0)})
[,1] [,2] [,3]
col1 "0" "B" "0"
col2 "D" "B" "0"
col3 "0" "0" "X"
并将其转换回data.frame:
as.data.frame(apply(test2, 1, function(x) {replace(x, x=="A", 0)}))