我不确定标题的措辞是否正确,我对R有点新。我正在使用一个毫无意义的任务来刷新我的记忆。我有一些美国人口数据。 我想要做的是制作一个贯穿的for循环并绘制每个州的人口。这是我到目前为止所做的。现在我正在试图弄清楚如何打印人口作为测试。
a <- split(data,list(state)) ##split factor state into individual states
例如str(a$'Alabama'$Population)
是我想要绘制的种群的数字。
for(i in 1:53){
b <- noquote((paste(c("a","$", "'",state.list[i],"'", "$","Population"),collapse="")))
}
现在如果我打印(b)输出是$&#39; Alabama&#39; $ Population,但str(print(b))表示它是一个角色。如果我能把它变成数字,我可以继续我的代码的下一部分。
这有意义吗?
任何提示都表示赞赏。由于这是我的学习练习,我想知道如何解决这个问题。但是,我愿意接受更好的方法。
dput(head(data, 10))
structure(list(State = structure(c(46L, 1L, 2L, 3L, 4L, 5L, 6L,
7L, 8L, 9L), .Label = c("Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware", "District of Columbia",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana",
"Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland",
"Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri",
"Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota", "Ohio",
"Oklahoma", "Oregon", "Pennsylvania", "Puerto Rico", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas", "United States",
"Utah", "Vermont", "Virginia", "Washington", "West Virginia",
"Wisconsin", "Wyoming"), class = "factor"), Population = c(308.745538,
4.779736, 0.710231, 6.392017, 2.915918, 37.253956, 5.029196,
3.574097, 0.897934, 0.601723), Year = structure(c(6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L), .Label = c("2,010", "2,011", "2,012",
"2,013", "2,014", "Census"), class = "factor")), .Names = c("State",
"Population", "Year"), row.names = c(NA, 10L), class = "data.frame")
链接到完整dput
:http://pastebin.com/Mg16q67m
答案 0 :(得分:3)
如果你使用基本图形,你可能需要单独绘制图形,但是格子或ggplot2可以更轻松地完成这项工作。以下内容消除了Census
值(这不是&#34;年&#34;),清除逗号“year
列并使用ggplot进行切面绘图每个州的人口增长。
library(ggplot2)
dat <- subset(dat, Year != "Census")
dat$Year <- sub(",", "", dat$Year)
gg <- ggplot(dat)
gg <- gg + geom_line(aes(x=Year, y=Population, group=State))
gg <- gg + geom_point(aes(x=Year, y=Population, group=State))
gg <- gg + scale_x_discrete(breaks=c("2010", "2012", "2014"))
gg <- gg + facet_wrap(~State, scale="free_y", ncol=5)
gg <- gg + labs(x=NULL, y=NULL, title="Population")
gg <- gg + theme_bw()
gg