我正在尝试使用名称中包含空格的列创建DF,但是出现错误。这是我要创建的DF:
CITY <- c('NEW YORK', 'LONDON', 'SAN FRANCISCO', 'MADRID', 'LOS ANGELES', 'LISBON', 'RIO DE JANEIRO', 'MOSCOW', 'SAO PAULO', 'TOKIO')
NEW YORK <- c(0, 700, 250, 1000, 400, 800, 430, 900, 500, 30)
LONDON <- c(700, 0, 350, 1200, 50, 110, 780, 984, 1150, 5)
SAN FRANCISCO <- c(250, 350, 0, 200, 15, 260, 305, 412, 29, 102)
MADRID <- c(1000, 1200, 200, 0, 77, 115, 225, 318, 412, 511)
LOS ANGELES <- c(400, 50, 15, 77, 0, 88, 819, 733, 978, 1001)
LISBON <- c(800, 110, 260, 115, 88, 0, 17, 3000, 1418, 735)
RIO DE JANEIRO <- c(430, 780, 305, 225, 819, 17, 0, 513, 701, 56)
MOSCOW <- c(900, 984, 412, 318, 733, 3000, 513, 0, 389, 499)
SAO PAULO <- c(500, 1150, 29, 412, 978, 1418, 701, 389, 0, 1113)
TOKIO <- c(30, 5, 102, 511, 1001, 735, 56, 499, 1113, 0)
DF <- data.frame(CITY, NEW YORK, LONDON, SAN FRANCISCO, MADRID, LOS ANGELES, LISBON, RIO DE JANEIRO, MOSCOW, SAO PAULO, TOKIO)
这是错误消息:
Error: unexpected symbol in "NEW YORK"
如何解决这个问题示例?我正在处理的DF像本例一样有几列,所以我想提出一个解决方案建议,该建议可以涵盖多列。
答案 0 :(得分:1)
变量名称不能有空格,因为空格将被解释为单独的标记,这就是您的错误出处。我已修改您的示例,使其与您的期望尽可能接近:
CITY <- c('NEW YORK', 'LONDON', 'SAN FRANCISCO', 'MADRID', 'LOS ANGELES', 'LISBON', 'RIO DE JANEIRO', 'MOSCOW', 'SAO PAULO', 'TOKIO')
NEW_YORK <- c(0, 700, 250, 1000, 400, 800, 430, 900, 500, 30)
LONDON <- c(700, 0, 350, 1200, 50, 110, 780, 984, 1150, 5)
SAN_FRANCISCO <- c(250, 350, 0, 200, 15, 260, 305, 412, 29, 102)
MADRID <- c(1000, 1200, 200, 0, 77, 115, 225, 318, 412, 511)
LOS_ANGELES <- c(400, 50, 15, 77, 0, 88, 819, 733, 978, 1001)
LISBON <- c(800, 110, 260, 115, 88, 0, 17, 3000, 1418, 735)
RIO_DE_JANEIRO <- c(430, 780, 305, 225, 819, 17, 0, 513, 701, 56)
MOSCOW <- c(900, 984, 412, 318, 733, 3000, 513, 0, 389, 499)
SAO_PAULO <- c(500, 1150, 29, 412, 978, 1418, 701, 389, 0, 1113)
TOKIO <- c(30, 5, 102, 511, 1001, 735, 56, 499, 1113, 0)
DF <- data.frame(CITY, `NEW YORK` = NEW_YORK, LONDON, `SAN FRANCISCO` = SAN_FRANCISCO, MADRID, `LOS ANGELES` = LOS_ANGELES, LISBON, `RIO DE JANEIRO` = RIO_DE_JANEIRO, MOSCOW, `SAO PAULO` = SAO_PAULO, TOKIO, check.names = FALSE)
参数check.names = FALSE
是为了防止R消除列名中的空格,谢谢@MrFlick!
print(DF)
CITY NEW YORK LONDON SAN FRANCISCO MADRID LOS ANGELES LISBON RIO DE JANEIRO MOSCOW SAO PAULO TOKIO
1 NEW YORK 0 700 250 1000 400 800 430 900 500 30
2 LONDON 700 0 350 1200 50 110 780 984 1150 5
3 SAN FRANCISCO 250 350 0 200 15 260 305 412 29 102
4 MADRID 1000 1200 200 0 77 115 225 318 412 511
5 LOS ANGELES 400 50 15 77 0 88 819 733 978 1001
6 LISBON 800 110 260 115 88 0 17 3000 1418 735
7 RIO DE JANEIRO 430 780 305 225 819 17 0 513 701 56
8 MOSCOW 900 984 412 318 733 3000 513 0 389 499
9 SAO PAULO 500 1150 29 412 978 1418 701 389 0 1113
10 TOKIO 30 5 102 511 1001 735 56 499 1113 0