【发布时间】:2016-11-23 02:03:15
【问题描述】:
以下Employee 表来自http://www.analyticsvidhya.com/blog/2015/12/sql-commands-common-excel-operations/。该表后面的代码基于示例 8B。
Employee <- structure(list(ECODE = c("A011", "A001", "A007"), DOJ =
c("3-Jul-12", "12-Jun-12", "13-Aug-12"), Experience = c(2.1, 2.2, 2),
Gender = c("Male", "Male", "Female"), Department = c("Support", "Admin",
"Support"), No_Of_Hours = c(17.42, 15.45, 13.54), Pay_Per_Hours = c(40L,
45L, 44L), Total_Payout = c(696.8, 695.25, 595.72), City = c("Delhi",
"Delhi", "Mumbai")), .Names = c("ECODE", "DOJ", "Experience", "Gender",
"Department", "No_Of_Hours", "Pay_Per_Hours", "Total_Payout", "City"),
row.names = c(NA, -3L), class = c("data.table", "data.frame"))
# Employee
# ECODE DOJ Experience Gender Department No_Of_Hours
# 1: A011 3-Jul-12 2.1 Male Support 17.42
Pay_Per_Hours
40
# 2: A001 12-Jun-12 2.2 Male Admin 15.45
45
# 3: A007 13-Aug-12 2.0 Female Support 13.54
44
# Total_Payout City
# 1: 696.80 Delhi
# 2: 695.25 Delhi
# 3: 595.72 Mumbai
在示例 8B 中使用了 [LEFT(x,N)],但我发现 Leftstr (how to use right/left to split a variable in sqldf, as in left(x,n)) 是在 sqldf 中完成的方式。
由于列名中没有特殊字符(“.”),因此操作按预期进行。
sqldf("Select *, Leftstr(City,3) as 'City_Code' from Employee where
Department = 'Admin'")
# ECODE DOJ Experience Gender Department No_Of_Hours
# 1 A001 12-Jun-12 2.2 Male Admin 15.45
# Pay_Per_Hours Total_Payout City City_Code
# 45 695.25 Delhi Del
在下面的示例中,这与我的真实数据集相似,列名中有句点,答案不是预期的。
sqldf("Select *, Leftstr('City.1',3) as 'City_Code' from Employee where
Department = 'Admin'")
# ECODE DOJ Experience Gender Department No_Of_Hours
# 1 A001 12-Jun-12 2.2 Male Admin 15.45
# Pay_Per_Hours Total_Payout City City_Code
# 45 695.25 Delhi Cit
当leftstr操作的列名中有特殊字符时,sqldf代码需要做什么?
【问题讨论】: