问题
I have a data frame and has columns like this:
gene col1 col2 type
------------------------------
gene_1 a b 1
gene_2 aa bb 2
gene_3 a b 1
gene_4 aa bb 2
I want to find the column "type" using column "col2" and "col1". so I need a classification based on "col2" and "col1". how should I do this in R?
thanks a lot
回答1:
Based. on the output, an option is to create group indices from columns 'col1', and 'col2'
library(dplyr)
df1 %>%
mutate(type = group_indices(., col1, col2))
#. gene col1 col2 type
#1 gene_1 a b 1
#2 gene_2 aa bb 2
#3 gene_3 a b 1
#4 gene_4 aa bb 2
If there are multiple names, then one option is to convert the string column names to sym
bols and then evaluate (!!!
)
df1 %>%
mutate(type = group_indices(., !!! rlang::syms(names(.)[2:3])))
Or in data.table
library(data.table)
setDT(df1)[, type := .GRP, .(col1, col2)]
data
df1 <- structure(list(gene = c("gene_1", "gene_2", "gene_3", "gene_4"
), col1 = c("a", "aa", "a", "aa"), col2 = c("b", "bb", "b", "bb"
), type = c(1L, 2L, 1L, 2L)), class = "data.frame", row.names = c(NA,
-4L))
来源:https://stackoverflow.com/questions/57807997/how-to-classify-data-frame-based-on-a-columns-in-r