Assigning values to a df$column based on another column in the same df

后端 未结 2 495
情书的邮戳
情书的邮戳 2021-01-29 04:33
df2 <- data.frame(Mean = c(.5,4,2.3,1.2,3.7,3.3,.8), Numbers = \"NA\")


for(i in 1:length(df2$Mean)){
        if(df2$Mean[i] <= .5) {
        df2$Number[i] = 0
           


        
2条回答
  •  深忆病人
    2021-01-29 04:46

    df$Number <- findInterval( df$Mean, c( seq(0.5, 3.5, by=1) , Inf) )
    

    There was an edge case where df$Mean = 3.5 that was not covered by your definition. My method gives it a 4.

    The findInterval function is really doing something very similar to the cut function, except it returns a numeric value rather that a factor. It sets up a bunch of intervals and tells you which interval each item would fall into.

提交回复
热议问题