簡體   English   中英

如何將現有列中的負值提取到新列中

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

我有一個 dataframe (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)

Output

     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

這兩個解決方案都有效!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM