假设我有一个向量,其中包含
a
中的一系列半径,以及 circle_stats
中从 1 到 30 的半径的面积和周长。我想要对 circle_stats
进行子集化,以使行与 a
中找到的行匹配。
a <- as.character(c(1,2,3,4,5,5,6,7,2,8,4,9,10,10,1,1,1,1,1,4))
unique(a[duplicated(a)])
# these are the duplicated values
# 5 2 4 10 1
radius <- c(1:30)
circle_stats <- data.frame(radius=as.character(radius),
area=pi*radius^2,
circumference=2*pi*radius)
这也意味着能够保留重复项而不是丢弃它们,或者从
circle_stats
提取 20 行而不是仅仅 10 行。
这是我尝试过的:
library(data.table)
circle_stats %>%
subset(radius %in% a) %>%
arrange(match(radius, a))
radius area circumference
1 1 3.141593 6.283185
2 2 12.566371 12.566371
3 3 28.274334 18.849556
4 4 50.265482 25.132741
5 5 78.539816 31.415927
6 6 113.097336 37.699112
7 7 153.938040 43.982297
8 8 201.061930 50.265482
9 9 254.469005 56.548668
10 10 314.159265 62.831853
如您所见,问题是我无法保留重复项,我认为这需要
subset
函数中的参数或函数。我就是不知道是哪一个。
非常感谢任何帮助!
编辑:最初问题考虑的是数值,但我正在使用的数据集使用
a
和 circle_stats$radius
中的字符值。
谢谢@lotus的回答:
library(dplyr)
circle_stats %>%
dplyr::slice(match(a, radius))
radius area circumference
1 1 3.141593 6.283185
2 2 12.566371 12.566371
3 3 28.274334 18.849556
4 4 50.265482 25.132741
5 5 78.539816 31.415927
6 5 78.539816 31.415927
7 6 113.097336 37.699112
8 7 153.938040 43.982297
9 2 12.566371 12.566371
10 8 201.061930 50.265482
11 4 50.265482 25.132741
12 9 254.469005 56.548668
13 10 314.159265 62.831853
14 10 314.159265 62.831853
15 1 3.141593 6.283185
16 1 3.141593 6.283185
17 1 3.141593 6.283185
18 1 3.141593 6.283185
19 1 3.141593 6.283185
20 4 50.265482 25.132741