【问题标题】:how to change a column with both negative and positive value into two columns with negative value plus zero and positive value plus zero如何将具有负值和正值的列更改为具有负值加零和正值加零的两列
【发布时间】:2019-12-26 06:11:47
【问题描述】:

我的数据如下:

t  B
1  2
2 -3
3 -7  

我怎么能得到像下面这样的输出?这意味着当B列的数据为负数时,N列将等于B列的数据,否则为零。相反,当 B 列的数据为正时,P 列将等于该数据,否则将等于 0。

t   B  N  P
1   2  0  2
2  -3 -3  0
3  -7 -7  0

【问题讨论】:

    标签: r if-statement dplyr


    【解决方案1】:

    我们可以在这里使用pmin/pmax

    transform(df, N = pmin(B, 0), P = pmax(B, 0))
    
    #   B  N P
    #1  2  0 2
    #2 -3 -3 0
    #3 -7 -7 0
    

    另一种方法可能是

    transform(df, N = B * (B < 0), P = B * (B > 0))
    

    数据

    df<- structure(list(B = c(2L, -3L, -7L)), class = "data.frame", 
         row.names = c("1", "2", "3"))
    

    【讨论】:

      【解决方案2】:

      我们可以在这里使用ifelse 作为基本 R 选项:

      df <- data.frame(t=c(1:3), B=c(2, -3, -7))
      df$N <- ifelse(df$B < 0, df$B, 0)
      df$P <- ifelse(df$B >= 0, df$B, 0)
      df
      
        t  B  N P
      1 1  2  0 2
      2 2 -3 -3 0
      3 3 -7 -7 0
      

      【讨论】:

        【解决方案3】:

        我们也可以

        library(dplyr)
        df %>% 
           rowwise %>% 
           mutate(N = min(B, 0), P = max(B, 0))
        # A tibble: 3 x 3
        #      B     N     P
        #  <int> <dbl> <dbl>
        #1     2     0     2
        #2    -3    -3     0
        #3    -7    -7     0
        

        数据

        df<- structure(list(B = c(2L, -3L, -7L)), class = "data.frame", 
             row.names = c("1", "2", "3"))
        

        【讨论】:

          猜你喜欢
          • 2013-11-24
          • 2021-01-28
          • 2012-07-03
          • 1970-01-01
          • 2020-02-25
          • 1970-01-01
          • 1970-01-01
          • 2022-12-19
          • 1970-01-01
          相关资源
          最近更新 更多