如何将现有列中的负值提取到新列中

How can I extract negative values from an existing column into a new column

我有一个数据框 (sy2.1),其中有一列 (Vannstand2.cm) 包含水位的正值和负值。我想将负值和正值分成两个新列,同时仍保留原始列。我尝试使用以下代码改变负值:

sy2.1 %>% 
  group_by(Vannstand2.cm) %>% 
  mutate(Vannstand2_neg=case_when(Vannstand2.cm<0.0))

那没有用,错误抱怨负值,即使我特别要求只将所有内容移动到 0.0 以下。我也尝试了其他几种代码,但似乎没有任何效果..

这个问题还有其他代码吗?

要么使用 if_else:

sy2.1 %>% 
  group_by(Vannstand2.cm) %>% 
  mutate(Vannstand2_neg = if_else(Vannstand2.cm < 0.0, 0, NA))

或 case_when

sy2.1 %>% 
  group_by(Vannstand2.cm) %>% 
  mutate(Vannstand2_neg = case_when(Vannstand2.cm < 0.0 ~ 0))

这是一个使用 tidyr::separate 的解决方案:

sy2.1 %>% tidyr::separate(col = Vannstand2.cm, sep = "(?=-)", 
                   into = c("Vannstand2Positive","Vannstand2Negative"), 
                   convert = T, remove = F)

"(?=-)"- 分隔列并保留在右列(更多信息请参见 ),remove = F 保留原始列。

玩具数据示例:

df <- data.frame(col1 = -10:10)
tidyr::separate(df, col = col1, sep = "(?=-)", into = c("positive","negative"), 
         convert = T, remove = F)

输出

     a positive negative
1  -10       NA      -10
2   -9       NA       -9
3   -8       NA       -8
4   -7       NA       -7
5   -6       NA       -6
6   -5       NA       -5
7   -4       NA       -4
8   -3       NA       -3
9   -2       NA       -2
10  -1       NA       -1
11   0        0       NA
12   1        1       NA
13   2        2       NA
14   3        3       NA
15   4        4       NA
16   5        5       NA
17   6        6       NA
18   7        7       NA
19   8        8       NA
20   9        9       NA
21  10       10       NA