这就是它的样子:
Maths Rank
Good 1
VeryGood 2
3 NA
4 NA
5 NA
这应该是它的样子:
Maths Rank
Good 1
VeryGood 2
NA 3
NA 4
NA 5
答案 0 :(得分:1)
非常类似于akrun的方法。唯一的区别是,在符合条件时交换列:
test[is.na(test$Rank), ] <- test[is.na(test$Rank), c(2,1)]
或为了清楚起见:
index <- is.na(test$Rank)
test[index, ] <- test[index, c(2, 1)]
输出:
Maths Rank
1 Good 1
2 VeryGood 2
3 <NA> 3
4 <NA> 4
5 <NA> 5
数据:
Maths <- c("Good", "VeryGood", 3, 4, 5)
Rank <- c(1,2,NA,NA,NA)
test <- data.frame(Maths,Rank, stringsAsFactors = FALSE)
答案 1 :(得分:0)
Maths <- c("Good", "VeryGood", 3, 4, 5)
Rank <- c(1,2,NA,NA,NA)
test <- cbind(Maths,Rank)
test
for (i in 1:length(Rank)){
Rank[i] <- ifelse(is.na(Rank[i]),Maths[i],Rank[i])
Maths[i] <- ifelse(Maths[i]==Rank[i],NA,Maths[i])
}
test <- cbind(Maths,Rank)
test
CNC中 看scoa的评论*