例如,我有 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")
Run Code Online (Sandbox Code Playgroud)
有没有另一种方法可以做到这一点?我发现这段代码非常丑陋且不理想。
将要保留的值存储在 data.frame 中
keep <- read.table(text="
state city
1 1
2 4
3 3
4 2
5 101", header=T)
Run Code Online (Sandbox Code Playgroud)
然后合并以只保留匹配的行
country <- merge(country, keep)
Run Code Online (Sandbox Code Playgroud)