0

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

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

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

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

4

2 回答 2

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
于 2022-01-03T10:51:26.413 回答
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))
于 2022-01-03T10:40:22.727 回答