我试图在一个循环中使用R中的“where”函数,根据匹配元素从两个数据集中挑出某一行,然后制作两者的散点图。下面的代码示例提供了两个数据帧和循环的行名称。每个数据框包含的县比“mycounties”中列出的县多。
我之前在循环中使用了“where”函数,但是这次R返回错误消息“where”不存在?我知道“哪里”存在!我的问题是,如何让R识别这个“where”结构,还是有更好的方法来挑选我想要绘制的行?谢谢!
> names(dts)
[1] "county" "Freq125" "Freq126" "Freq127" "Freq128" "Freq129" "Freq130" "Freq131" "Freq132" "Freq133" "Freq134" "Freq135" "Freq136" "Freq137"
[15] "Freq138" "Freq139" "Freq140" "Freq141" "Freq142" "Freq143" "Freq144" "Freq145" "Freq146" "Freq147" "Freq148" "Freq149" "Freq150" "Freq151"
[29] "Freq152" "Freq153" "Freq154" "Freq155" "Freq156" "Freq157" "Freq158" "Freq159" "Freq160" "Freq161" "Freq162" "Freq163" "Freq164" "Freq165"
[43] "Freq166" "Freq167" "Freq168" "Freq169" "Freq170" "Freq171"
> names(pm)
[1] "county" "pm125m" "pm126m" "pm127m" "pm128m" "pm129m" "pm130m" "pm131m" "pm132m" "pm133m" "pm134m" "pm135m" "pm136m" "pm137m" "pm138m"
[16] "pm139m" "pm140m" "pm141m" "pm142m" "pm143m" "pm144m" "pm145m" "pm146m" "pm147m" "pm148m" "pm149m" "pm150m" "pm151m" "pm152m" "pm153m"
[31] "pm154m" "pm155m" "pm156m" "pm157m" "pm158m" "pm159m" "pm160m" "pm161m" "pm162m" "pm163m" "pm164m" "pm165m" "pm166m" "pm167m" "pm168m"
[46] "pm169m" "pm170m" "pm171m"
>
> mycounties = c("beaufort", "bertie", "bladen", "camden", "carteret", "chowan", "craven",
+ "cumberland", "currituck", "dare", "duplin", "gates", "greene", "harnett", "hyde",
+ "jones", "lenoir", "new hanover", "onslow", "pamlico", "pasquotank", "pender", "perquimans", "pitt", "robeson", "sampson", "tyrrell", "washington")
>
> LOOP
> for (i in 1:length(mycounties)) {
+ x = pm[where(pm$county == mycounties[i]),2:48]
+ y = dt[where(dts$county == mycounties[i]),2:48 ]
+ plot( x, y, main=paste("HYSPLIT & ED Visits", counties[i], sep=""),
+ xlab="HYSPLIT", ylab="ED Visits", pch=19)
+ }
Error in `[.data.frame`(pm, where(pm$county == mycounties[i]), 2:48) :
could not find function "where"
答案 0 :(得分:5)
which
是R版本。
但是,在此示例中,您根本不需要which
:
x <- pm[pm$county == mycounties[i], 2:48]
y <- dt[dt$county == mycounties[i], 2:48]
同样在您的示例if
声明中:
if (mat$county[i] %in% dt5$county)) {
mat[i,2:58] = dt5[dt5$county == mat$county[i], 2:58]
}
假设您的dt5$county
每个mat$county[i]
只有一个匹配的县。否则你会收到错误。
答案 1 :(得分:3)
您是否尝试引用which()
功能?