How to Classify data frame Based on a Columns in R? [duplicate]

丶灬走出姿态 提交于 2020-01-05 08:29:41

问题


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 symbols 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!