我正试图通过在R中添加两个现有的数值变量来生成一个新变量。我知道我可以使用以下代码,它成功了。
这是一个数据示例:
B01001_SEX_BY_AGE <- structure(list(GEOID = "04000US17", `Geography Name` = "Illinois",
`Total Population` = 12851684, Male = 6310460, `Male: Under 5 years` = 403373, `Female: Under 5 years` = 406002), row.names = c(NA,
-1L), class = c("tbl_df", "tbl", "data.frame"))
B01001_SEX_BY_AGE$"Under 5 years"= B01001_SEX_BY_AGE$"Male: Under 5 years" + B01001_SEX_BY_AGE$"Female: Under 5 years"
但正如您所看到的,我的数据框架和变量有很长的名称。因此,在这些表达式中必须同时引用数据帧和变量名可能会变得非常混乱。我尝试了以下几种方法,但都出现了相同的错误。CCD_ 1。我还尝试为这些变量添加as.numeric()
,并用下划线替换变量名中的空格,但仍然没有成功。
#Method 1
attach(B01001_SEX_BY_AGE)
B01001_SEX_BY_AGE$"Under 5 years"= "Male: Under 5 years" + "Female: Under 5 years"
detach(B01001_SEX_BY_AGE)
#Method 2
B01001_SEX_BY_AGE <- transform(B01001_SEX_BY_AGE,
"Under 5 years" = "Male: Under 5 years" + "Female: Under 5 years"
)
#Method 3
library(dplyr)
B01001_SEX_BY_AGE <- mutate(B01001_SEX_BY_AGE,"Under 5 years" = "Male: Under 5 years" + "Female: Under 5 years")
所有在控制台中返回以下错误:
Error in "Male Under 5 years" + "Female_Under_5_years" :
non-numeric argument to binary operator
我非常感谢你的帮助。谢谢
试着对带有空格的名称使用反引号而不是双引号
library(dplyr)
B01001_SEX_BY_AGE <- mutate(B01001_SEX_BY_AGE,`Under 5 years` = `Male: Under 5 years` + `Female: Under 5 years`)