如何在 R 数据框列中添加单引号到字符串?
为了在 R 数据框列中添加单引号到字符串,我们可以使用 paste0 函数。这将从两侧用单引号括住字符串,但我们也可以只在开头或结尾添加单引号。
要在两侧都添加单引号,可以使用以下语法:
Data_frame$Column<-paste0("'", Data_frame$Column,"'")
示例 1
以下代码片段创建了一个示例数据框:
x<-LETTERS[1:20] df1<-data.frame(x) df1
输出
创建了以下数据框:
x 1 A 2 B 3 C 4 D 5 E 6 F 7 G 8 H 9 I 10 J 11 K 12 L 13 M 14 N 15 O 16 P 17 Q 18 R 19 S 20 T
为了在 x 中每个值的左右两侧添加单引号,请在上述代码片段中添加以下代码:
x<-LETTERS[1:20] df1<-data.frame(x) df1$x<-paste0("'",df1$x,"'") df1
输出
如果您将上述所有代码作为单个程序执行,则会生成以下输出:
x 1 'A' 2 'B' 3 'C' 4 'D' 5 'E' 6 'F' 7 'G' 8 'H' 9 'I' 10 'J' 11 'K' 12 'L' 13 'M' 14 'N' 15 'O' 16 'P' 17 'Q' 18 'R' 19 'S' 20 'T'
示例 2
以下代码片段创建了一个示例数据框:
States_20<-c("Alabama", "Alaska", "American Samoa", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia", "Florida", "Georgia", "Guam", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky") df2<-data.frame(States_20) df2
输出
创建了以下数据框:
States_20 1 Alabama 2 Alaska 3 American Samoa 4 Arizona 5 Arkansas 6 California 7 Colorado 8 Connecticut 9 Delaware 10 District of Columbia 11 Florida 12 Georgia 13 Guam 14 Hawaii 15 Idaho 16 Illinois 17 Indiana 18 Iowa 19 Kansas 20 Kentucky
为了在 States_20 中每个值的左右两侧添加单引号,请在上述代码片段中添加以下代码:
States_20<-c("Alabama", "Alaska", "American Samoa", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia", "Florida", "Georgia", "Guam", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky") df2<-data.frame(States_20) df2$States_20<-paste0("'",df2$States_20,"'") df2
输出
如果您将上述所有代码作为单个程序执行,则会生成以下输出:
States_20 1 'Alabama' 2 'Alaska' 3 'American Samoa' 4 'Arizona' 5 'Arkansas' 6 'California' 7 'Colorado' 8 'Connecticut' 9 'Delaware' 10 'District of Columbia' 11 'Florida' 12 'Georgia' 13 'Guam' 14 'Hawaii' 15 'Idaho' 16 'Illinois' 17 'Indiana' 18 'Iowa' 19 'Kansas' 20 'Kentucky'
示例 3
以下代码片段创建了一个示例数据框:
States_Abb_20<-c("AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY") df3<-data.frame(States_Abb_20) df3
输出
创建了以下数据框:
States_Abb_20 1 AK 2 AL 3 AR 4 AS 5 AZ 6 CA 7 CO 8 CT 9 DC 10 DE 11 FL 12 GA 13 GU 14 HI 15 IA 16 ID 17 IL 18 IN 19 KS 20 KY
为了在 States_Abb_20 中每个值的左右两侧添加单引号,请在上述代码片段中添加以下代码:
States_Abb_20<-c("AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY") df3<-data.frame(States_Abb_20) df3$States_Abb_20<-paste0("'",df3$States_Abb_20,"'") df3
输出
如果您将上述所有代码作为单个程序执行,则会生成以下输出:
States_Abb_20 1 'AK' 2 'AL' 3 'AR' 4 'AS' 5 'AZ' 6 'CA' 7 'CO' 8 'CT' 9 'DC' 10 'DE' 11 'FL' 12 'GA' 13 'GU' 14 'HI' 15 'IA' 16 'ID' 17 'IL' 18 'IN' 19 'KS' 20 'KY'
广告