Updating a subset of a dataframe

后端 未结 2 1217
一向
一向 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条回答
  •  Happy的楠姐
    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
    

提交回复
热议问题