R: Extract list columns based on column names and patterns -
i have list (here sample data)
my_list <- list(structure(list(sample = c(2l, 6l), data1 = c(56l, 78l), data2 = c(59l, 27l), data3 = c(90l, 28l), data1namet = structure(c(1l, 1l), .label = "sam1", class = "factor"), data2namab = structure(c(1l, 1l), .label = "test2", class = "factor"), dataame = structure(c(1l, 1l), .label = "ex3", class = "factor"), ma = c("jay", "jay" )), .names = c("sample", "data1", "data2", "data3", "data1namet", "data2namab", "dataame", "ma"), row.names = c(na, -2l), class = "data.frame"), structure(list(sample = c(12l, 13l, 17l), data1 = c(56l, 78l, 3l), data2 = c(59l, 27l, 2l), datest = structure(c(1l, 1l, 1l), .label = "exa9", class = "factor"), dattestr = structure(c(1l, 1l, 1l), .label = "cz1", class = "factor"), add = c(2, 2, 2)), .names = c("sample", "data1", "data2", "datest", "dattestr", "add"), row.names = c(na, -3l), class = "data.frame")) my_list [[1]] sample data1 data2 data3 data1namet data2namab dataame ma 1 2 56 59 90 sam1 test2 ex3 jay 2 6 78 27 28 sam1 test2 ex3 jay [[2]] sample data1 data2 datest dattestr add 1 12 56 59 exa9 cz1 2 2 13 78 27 exa9 cz1 2 3 17 3 2 exa9 cz1 2
i've got 2 problems: extract columns in list based on patterns of column names, e.g. columns contain word 'data' in column name. wasn't able find solution grep
.
i know how extract 1 column based on index number (see example below), how selection directly based on column name (not column number)?
out <- lapply(my_list, `[`, 1) # extract "sample" column
try
lapply(my_list, function(df) df[, grep("data", names(df), fixed = true)] ) # [[1]] # data1 data2 data3 data1namet data2namab dataame # 1 56 59 90 sam1 test2 ex3 # 2 78 27 28 sam1 test2 ex3 # # [[2]] # data1 data2 # 1 56 59 # 2 78 27 # 3 3 2 lapply(my_list, "[", "sample") # [[1]] # sample # 1 2 # 2 6 # # [[2]] # sample # 1 12 # 2 13 # 3 17
Comments
Post a Comment