R 如何用相邻列中的数据替换列中的NA值?

R 如何用相邻列中的数据替换列中的NA值?,r,R,这就是它的样子: Maths Rank Good 1 VeryGood 2 3 NA 4 NA 5 NA 它应该是这样的: Maths Rank Good 1 VeryGood 2 NA 3 NA 4 NA 5 mathematics我们不需要循环就可以做到这一点。我们为“Rank”列中

这就是它的样子:

   Maths   Rank
    Good      1
VeryGood      2
       3     NA
       4     NA
       5     NA
它应该是这样的:

   Maths   Rank
    Good      1
VeryGood      2
      NA      3
      NA      4
      NA      5

mathematics我们不需要循环就可以做到这一点。我们为“Rank”列中的“NA”值创建一个逻辑索引(
is.NA(df1$Rank)
)。使用它,我们可以将“Rank”中的“NA”值替换为“math”中的相应值。在最后一步中,根据“indx”替换与“NA”对应的“数学”值

  indx <- is.na(df1$Rank)
  df1$Rank[indx] <- df1$Maths[indx]
  df1$Maths[indx] <- NA
  df1
  #     Maths Rank
  #1     Good    1
  #2 VeryGood    2
  #3     <NA>    3
  #4     <NA>    4
  #5     <NA>    5

indx与akrun的方法非常相似。唯一的区别是,当满足条件时,在这里交换列:

test[is.na(test$Rank), ] <- test[is.na(test$Rank), c(2,1)]

test[is.na(test$Rank),]抱歉,Richard。。我是新来的……没关系。欢迎这里你真正需要包括的是一个关于你到底想做什么的解释。看起来您只是想将数字交换到下一列。是吗?是的,它是数据框的一部分,有大约300行条目。我试图做的是用存储在相邻列“math”中的值来填充列“Rank”中具有值“na”的一些行。这是因为数据是tilda分隔的,而数学列是空的。我也知道它可以很容易地在记事本中编辑。但是我想知道R中的过程。你不需要循环,你可以矢量化这个解决方案:
Rank@akrun对不起,这是真的。我认为唯一的区别是,您根据索引分配NA,而在我的代码中,我只是在满足条件的地方交换列。也许我错了,我现在注意到了。看起来很酷!我单独指定了它,以便更清楚一点。
df1 <- structure(list(Maths = c("Good", "VeryGood", "3", "4", "5"), 
Rank = c(1L, 2L, NA, NA, NA)), .Names = c("Maths", "Rank"
), class = "data.frame", row.names = c(NA, -5L))
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)