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
  • 52,746
  • 12
  • 114
  • 209
  • do a `coalesce` i.e. `library(dplyr);d1 %>% mutate(Name.x = coalesce(Name.x, Name.y)) %>% select(Name.x)` – akrun Feb 15 '18 at 10:44
  • 1
    If it is only 2 columns then try: `df1$Name.x <- ifelse(!is.na(df1$Name.y), df1$Name.y, df1$Name.x)` – zx8754 Feb 15 '18 at 10:53
  • it is a big dataset... this is just an example to make it simplier – user5879741 Feb 15 '18 at 10:54
  • Data can be big, but are you comparing only 2 columns or more? If more, then use coalesce as suggested by akrun. – zx8754 Feb 15 '18 at 10:56
  • i only want name.x column in this dataframe1 to be basically overwritten by dataframe2 only with condition that it is not empty. – user5879741 Feb 15 '18 at 11:05
  • Possible duplicate of [How to implement coalesce efficiently in R](https://stackoverflow.com/questions/19253820/how-to-implement-coalesce-efficiently-in-r) – Aramis7d Feb 15 '18 at 12:10
  • @akrun I think it should be `coalesce(Name.y, Name.x)`, going by the example provided. – Aramis7d Feb 15 '18 at 12:12
  • @Aramis7d Could be, I think there are some edits in the example – akrun Feb 15 '18 at 13:47

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
  • 16,303
  • 3
  • 35
  • 53
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,918
  • 2
  • 20
  • 39