0

I would like to replace the value of column Name.x with value from Name.y with condition if it is not NA (empty rows)

Name.x  Name.y
US      NA
Germany NA
Germany France
Canada  NA
Italy     Morocco
Austria Belgium

Result:

Name.x
US
Germany
France
Canada
Morocco
Belgium
zx8754
  • 46,390
  • 10
  • 104
  • 180

2 Answers2

1

Example data:

a <- data.frame("Name.x" = c("US", "Germany","Germany", "Canada", "Italy", "Austria"),  "Name.y" = c(NA, NA, "France", NA, "Morocco", "Belgium"))

Solution:

a$Name.x <- ifelse(is.na(a$Name.y), as.character(a$Name.x), as.character(a$Name.y))
duckmayr
  • 15,718
  • 3
  • 32
  • 50
R.Y
  • 21
  • 1
  • 1
    Welcome to `stackoverflow`. Please always try to explain what you're doing in the code. It's not really helpful to just submit unformatted code without any explanations. – Aramis7d Feb 15 '18 at 12:09
  • 1
    This is a good answer. The downvote is a bit harsh here especially considering that the code is self explanatory. – Sotos Feb 15 '18 at 13:35
0

Try something like this:

Your data.frame

 db1<-data.frame(Name.x=c("US","Germany"),
                 Name.y=c(NA,"France"))
   db1
   Name.x Name.y
      US   <NA>
 Germany France

Columns names to analyze/substitute

coldb1_NA<-"Name.y"
coldb_toSub<-"Name.x"

Substitution

db2<-db1
db2[,coldb_toSub]<-as.character(db1[,coldb_toSub])
db2[!is.na(db1[,coldb1_NA]),coldb_toSub]<-as.character(db1[!is.na(db1[,coldb1_NA]),coldb1_NA])

Your output

db2
  Name.x Name.y
1     US   <NA>
2 France France
Terru_theTerror
  • 4,788
  • 2
  • 17
  • 37