替代R中的子集?

例如,我有 5 个州和每个州的多个城市。我想每个州只选择 1 个城市。我正在尝试这个代码:

country <- subset(country, country$state == "1" & country$city == "1" |  
                           country$state == "2" & country$city == "4" |
                           country$state == "3" & country$city == "3" | 
                           country$state == "4" & country$city == "2" |
                           country$state == "5" & country$city == "101")

有没有另一种方法可以做到这一点?我发现这段代码非常丑陋且不理想。

回答

将要保留的值存储在 data.frame 中

keep <- read.table(text="
state city
1 1
2 4
3 3
4 2
5 101", header=T)

然后合并以只保留匹配的行

country  <- merge(country, keep)


以上是替代R中的子集?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>