[英]Character columns being converted to numeric when appending to SQL Server Database with DBI package in R
I have a database hosted using Microsoft SQL Server.我有一个使用 Microsoft SQL Server 托管的数据库。 It has a table
project
with columns project_id
( int identity
), project_code
( nvarchar not null
), and api_form
( nvarchar
).它有一个包含
project_id
( int identity
)、 project_code
( nvarchar not null
) 和api_form
( nvarchar
) 列的表project
。 I have connected to this using the DBI
package in R and ran the following code.我已经使用 R 中的
DBI
包连接到它并运行了以下代码。
dbAppendTable(conn, 'project', data.frame(
project_code = c("ABC123", "DEF456"),
api_form = c(NA, NA)
))
When I query the entire table however, I get the following output.但是,当我查询整个表时,我得到以下输出。
project_id project_code api_form
1 1 NULL
2 2 NULL
I am not sure why the characters are now integers.我不确定为什么字符现在是整数。 Is there a way to add character data directly to the table or, if this is expected behaviour, how do I query the table to find the actually text I entered?
有没有办法将字符数据直接添加到表格中,或者,如果这是预期的行为,我如何查询表格以找到我输入的实际文本?
Classic overlook of data.frame()
call that casts strings as factors by default.默认情况下将字符串转换为因子的
data.frame()
调用的经典忽略。 Your project_code
renders as factor (ie, numeric columns with label values) and not characters.您的
project_code
呈现为因子(即带有标签值的数字列)而不是字符。 To resolve, simply pass stringsAsFactors=FALSE
, so actual character values are appended to database table:要解决,只需传递
stringsAsFactors=FALSE
,这样实际的字符值就会附加到数据库表中:
dbAppendTable(conn, 'project',
data.frame(
project_code = c("ABC123", "DEF456"),
api_form = c(NA, NA),
stringsAsFactors=FALSE
)
)
Alternatively, set the argument as global option for all data.frame()
calls in your R session:或者,将参数设置为 R 会话中所有
data.frame()
调用的全局选项:
options(stringsAsFactors = FALSE)
dbAppendTable(conn, 'project',
data.frame(
project_code = c("ABC123", "DEF456"),
api_form = c(NA, NA)
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.