是否可以通過僅指示所需條目的字符串來提取/子集數據框?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