我正在尝试通过在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"
但是正如您所看到的,我为数据框和变量起了很长的名字。因此,必须在这些表达式中同时引用数据帧和变量名称,会变得很混乱。我尝试了以下替代方法,但是它们都遇到了相同的错误。 Evaluation ERROR: non-numeric argument to binary operator
。我还尝试为这些变量添加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
非常感谢您的帮助。谢谢。
答案 0 :(得分:1)
对于带空格的名称,请尝试使用反引号代替双引号
library(dplyr)
B01001_SEX_BY_AGE <- mutate(B01001_SEX_BY_AGE,`Under 5 years` = `Male: Under 5 years` + `Female: Under 5 years`)