是否可以通过仅指示所需条目的字符串来提取/子集数据框?R:子集/所需条目的子字符串索引对象
过滤条件存储在因子向量中。但只有前三位数字表示。这应该确定将从数据框开始的所有条目集合起来。
例子:
# Input dataframe
data <- read.table(header=T, text='
ID sex size
0120010 M 7
0120020 F 6
0121031 F 9
0130010 M 11
0130020 M 11
0130030 F 14
0130040 M 11
0150030 F 11
0150110 F 12
0180030 F 9
1150110 F 12
9180030 F 9
'colClasses =c("character", "factor", "integer"))
# Input vector/factor with the ID chunk, containing only the fist three digits
# of the targeted entries in data$ID
IDfilter <- c("012", "015", "115")
# My try/idea which sadly is not working - PLEASE HELP HERE
subset <- data[ID %in% paste(IDfilter, "?.", sep=""),]
# Expected subset
> subset
ID sex size
1 0120010 M 7
2 0120020 F 6
3 0121031 F 9
4 0150030 F 11
5 0150110 F 12
6 1150110 F 12
谢谢! :)
@Jilber很好! :) 谢谢! “as.numeric”部分重要吗?在我原来的问题中,我也有领先的零。 – alex
我编辑了我的答案,以说明引导零时存在的情况。在这种情况下,'ID'假设为'字符',以便允许第一个数字为'02002'中的'0',否则(如果是数字或整数)该数字将是'2002'。 –
非常感谢!它完美的工作! :) – alex