0

I tried using this query below in concatenation that I found in this forum as well:

DataFrame <- sqldf("select FirstName, LastName, MiddleName, FirstName || ' ' || MiddleName || ' ' || LastName as FullName from People")

Unfortunately if for example, MiddleName has no data or NA in the row, FullName also becomes NA despite the fact there is a LastName and FirstName. Same goes with the other columns.

  • 1
    I can replicate the `NA` issue, but a blank field for MiddleName `""` seems to work okay - e.g., using `People <- data.frame( FirstName=c("Joe","Dave", "John"), MiddleName=c(NA,"Alan", ""), LastName=c("Bloggs","Davies","Smith") )` – thelatemail May 05 '21 at 00:28

1 Answers1

1

Stealing from this previous comment here - String concatenation does not work in SQLite - this is really an SQLite issue, rather than an sqldf issue.

Since NULL || "text" returns NULL but '' || "text" returns '' you need to replace with blank text using coalesce() or ifnull():

library(sqldf)

People <- data.frame(
  FirstName=c("Joe","Dave", "John"),
  MiddleName=c(NA,"Alan", ""),
  LastName=c("Bloggs","Davies","Smith")
)


sqldf("
  select
    FirstName,
    LastName,
    MiddleName,
    FirstName || ' ' || MiddleName || ' ' || LastName as FullName,
    FirstName || ' ' || coalesce(MiddleName,'') || ' ' || coalesce(LastName,'') as FullFix
  from People
")

#  FirstName LastName MiddleName         FullName          FullFix
#1       Joe   Bloggs       <NA>             <NA>      Joe  Bloggs
#2      Dave   Davies       Alan Dave Alan Davies Dave Alan Davies
#3      John    Smith                 John  Smith      John  Smith
thelatemail
  • 91,185
  • 12
  • 128
  • 188