我有一个在1995-2005年间获得未达标状态的每个州的县的列表。
我想知道每个州每年有多少个县获得了这一地位。
如果我的数据格式是这样的,
State1 Country1 YR1 Yr2 Yr3 Yr4...
State1 Country2 YR1 Yr2 Yr3 Yr4
State2 County1 Yr1 Yr2.....每个年份变量可以有1或0,因为一个县可能在一段时间内获得或失去此状态。
我需要每年计算每个州有多少县处于未达标状态(YRx=1),但不知道如何做到这一点。
发布于 2010-06-19 02:51:40
我使用了以下示例:
data <- read.table(textConnection("
state county Yr1 Yr2 Yr3 Yr4
state1 county1 1 0 0 1
state1 county2 0 0 0 0
state1 county3 0 1 0 0
state1 county4 0 0 0 0
state1 county5 0 1 0 1
state2 county6 0 0 0 0
state2 county7 0 0 1 0
state2 county8 1 0 0 1
state2 county9 0 0 0 0
state2 county10 0 1 0 0
state3 county11 1 1 1 1
state3 county12 0 0 0 0
state3 county13 0 1 1 0
state3 county14 0 0 0 1
state4 county15 0 0 0 0
state4 county16 1 0 1 0
state4 county17 0 0 0 0
state4 county18 1 1 1 1
"), header = T)
library(reshape)
data2 <- melt(data, id = c("state", "county"))
cast(data2, state ~ variable, fun = sum)结果:
state Yr1 Yr2 Yr3 Yr4
1 state1 1 2 0 2
2 state2 1 1 1 1
3 state3 1 2 2 2
4 state4 2 1 2 1发布于 2010-06-19 02:30:24
这些数据是否被组织成一个数据帧?如果是这样,这些行是如何定义的?如果您的数据是这样组织的:
State County Year Attainment
State1 County1 1 1
State1 County1 2 0
State1 County1 3 1
State1 County1 4 1
State1 County2 1 1
State1 County2 2 1
...这样就有可能用一行代码就能得到你想要的汇总数据。希望你的符号意味着你的数据是这样组织的:
State County Yr1 Yr2 Yr3 Yr4
State1 County1 1 0 1 1
State1 County2 1 1 1 1使用reshape包中的melt()将此格式转换为上面列出的格式。
new.df <- melt(df, id = 1:2)它将称为年份变量variable和达到度变量value。现在,通过巧妙地使用reshape包中的cast函数,您可以获得所需的摘要。
counties <- cast(new.df, State ~ value, fun = length)
head(counties)但是,如果您的数据被组织为每个州、县和年份都是一列,并且它只有1行长,我认为您最好的下一步是重新格式化R之外的数据,使其看起来至少像我的第二个示例。
https://stackoverflow.com/questions/3071201
复制相似问题