我有一个农贸市场数据集,其中一列是“MarketName”(第2列),其中一列是“WIC”(第21栏)。如果WIC列= Y,我写了一个函数来检索市场名称。我的输出应该是2,207个名称的列表,但是我得到8,144行的输出,因为对于WIC列= N的行,我的输出显示NA 。有45列和8,144行,但这里是一个只有两列的假数据集
MarketName <- c("Union Springs Famers Market","Union Square Farmers Market", "Union Square Greenmarket", "Union Street Farmers Market", "Unity Market Day Farmers", "University Farmers Market")
WIC <- c("Y","N","N","N","Y","Y")
data3 <- data.frame(MarketName, WIC)
data3$MarketName <- as.character(data3$MarketName)
data3$WIC <- as.character(data3$WIC)
这是我的功能(可能是问题?)
marketacceptWIC <- function(mydf)
{
market <- 0
for(i in 1:length(data3$WIC))
{
if(data3[i,2] == "Y")
market[i] <- data3[i,1]
}
return(market)
}
这是我得到的输出样本
[1] "Union Springs Famers Market" NA NA NA
[5] "Unity Market Day Farmers" "University Farmers Market"
我想要的只是接受WIC的农贸市场清单
[1] "Union Springs Farmers' Market"
[2] "Unity Market Day Farmers"
[3] "University Farmers Market"
答案 0 :(得分:1)
我认为你不需要for
循环。尝试在WIC列上进行子集化。如果您只需要MarketName
列,那么
data3[data3$WIC == "Y", ]$MarketName
[1] "Union Springs Famers Market" "Unity Market Day Farmers" "University Farmers Market"