R - How to apply different functions to certain rows in a column

后端 未结 3 605
南笙
南笙 2021-02-06 13:30

I am trying to apply different functions to different rows based on the value of a string in an adjacent column. My dataframe looks like this:

type    size
A            


        
相关标签:
3条回答
  • 2021-02-06 14:04

    if you want you can nest the ifelses:

    df$size2 <- ifelse(df$type == "A", 3*df$size,
                           ifelse(df$type == "B", 1*df$size,
                               ifelse(df$type == "C", 2*df$size, NA)))
    
    
    #    > df
    #  type size size2
    #1    A    1     3
    #2    B    3     3
    #3    A    4    12
    #4    C    2     4
    #5    C    5    10
    #6    A    4    12
    #7    B   32    32
    #8    C    3     6
    
    0 讨论(0)
  • 2021-02-06 14:09

    This might be a might more R-ish (and I called my dataframe 'dat' instead of 'df' since df is a commonly used function.

    > facs <- c(3,1,2)
    > dat$size2= dat$size* facs[ match( dat$type, c("A","B","C") ) ]
    > dat
      type size size2
    1    A    1     3
    2    B    3     3
    3    A    4    12
    4    C    2     4
    5    C    5    10
    6    A    4    12
    7    B   32    32
    8    C    3     6
    

    The match function is used to construct indexes to supply to the extract function [.

    0 讨论(0)
  • 2021-02-06 14:11

    This could do it like this, creating separate logical vectors for each type:

    As <- df$type == 'A'
    Bs <- df$type == 'B'
    Cs <- df$type == 'C'
    df$size2[As] <- 3*df$size[As]
    df$size2[Bs] <- df$size[Bs]
    df$size2[Cs] <- 2*df$size[Cs]
    

    but a more direct approach would be to create a separate lookup table like this:

    df$size2 <- c(A=3,B=1,C=2)[as.character(df$type)] * df$size
    
    0 讨论(0)
提交回复
热议问题