Updating a subset of a dataframe

后端 未结 2 1207
一向
一向 2020-12-11 09:19

I have a dataframe as such

col.1 <- c(\"a\", \"b\", \"c\", \"d\", \"e\", \"b\", \"c\")
col.2 <- c(22, 33, 55, 66, 66, 22, 54)
df <- data.frame(col.1         


        
相关标签:
2条回答
  • 2020-12-11 09:44

    We could also use data.table. We convert the 'data.frame' to 'data.table' (setDT(df)), set the 'key' column as 'col.1', subset the rows with 'search.df', and assign (:=) the corresponding values of 'col.2' to 100. It should be fast for big datasets as we are replacing in place.

    library(data.table)#v1.9.6+
    setDT(df, key='col.1')[search.df, col.2 := 100]
    df
    #    col.1 col.2
    #1:     a    22
    #2:     b   100
    #3:     b   100
    #4:     c    55
    #5:     c    54
    #6:     d   100
    #7:     e    66
    
    0 讨论(0)
  • 2020-12-11 09:59
    df[df[,1] %in% search.df, 2] <- 100
    

    or if you want to use column elements of the data frame directly

    df$col.2[df$col.1 %in% search.df] <- 100
    

    For simplicity, the same broken down:

    # get index of rows to be updated by checking each value 
    # in col1 against search.df => e.g. FALSE, TRUE, FALSE, ...
    index <- df[,1] %in% search.df
    
    # update col2 where index is TRUE to a new value
    df[index, 2] <- 100
    
    0 讨论(0)
提交回复
热议问题