inanva
inanva

Reputation: 223

Using insert into with R

I am tring to using insert into sql syntax in R to insert row in data frame but is showing the following error:

(( error in sentax ))

Below is sample of my code:

Vector <- c("alex" ,"IT")
Tst <- data.frame( name.charcher(), major.charachter())
sqldf( c(" insert into Tst values (" , Vector[1] , "," ,Vector[2] , ")" , "select * from main.Tst "))

I hope my question is clear

Upvotes: 1

Views: 3561

Answers (1)

Julia Wilkerson
Julia Wilkerson

Reputation: 581

A few edits to help address the syntax error:

  • use a lower case s in the function name (sqldf() instead of Sqldf())
  • add a comma between "," and Vector[2]
  • add quotes around select * from main.Tst

Also, to note:

  • the 1d data structure for the heterogeneous content types in your Vector <- c("alex", 32) should be a list (rather than an atomic vector where all contents are of the same type).
  • depending on what database driver you're using, sqldf() may return an error if you try to insert values into an empty R data frame as you have in your code. Creating the empty data frame within the sqldf() call is one approach to avoid this (used below in absence of knowing your database info).

For example, you could use the following to resolve the error message you're getting:

library(sqldf)
new <- list(name='alex', age=as.integer(32)) 
Tst <- sqldf(c("create table T1 (name char, age int)",
               paste0("insert into T1 (name, age) values ('", new$name[1],"',", new$age[1],")",sep=''),
               "select * from T1"))
Tst
# > Tst
#   name age
# 1 alex  32

Upvotes: 2

Related Questions