vendredi 25 juin 2021

Looping for copying information from one column to the next in R

I have a dataframe like below:

test
#  Name1 Name2  Match
#1     A     C      1
#2     E     NA     0
#3     D     G      1
#4     R     NA     0

The match column shows 1 if both name columns have a non-NA element, and 0 when they don't. I'd like to create a way to read through a dataframe so that if test$match == 0, then the row element from Name 1 will be copied over to Name 2 to look like:

test
#  Name1 Name2  Match
#1     A     C      1
#2     E     E      0 #I don't care about the match column after the change
#3     D     G      1
#4     R     R      0

I've been trying to create a for loop with an if statement, but it simply removes the Name2 column.

test$Name2 <- for (i in 1:nrow(test)) {
  if (test$match == 0) {
      test$Name2[i] <- test$Name1[i]
    }
}

If there's a way to accomplish this without a for loop I'd be particularly interested in that as the dataset is large.

Aucun commentaire:

Enregistrer un commentaire