簡體   English   中英

從包含數字和字符的列創建間隔類別 R

[英]create interval categories from a column including both numbers and characters in R

假設我有以下數據,我想添加 c 列,如果 b 列僅包含正值或負值,則我有類別<0, 0, 0-3, >3否則 c 列中的類別將是 b 列包含的任何內容。

df <- data.frame(a= 1:14,
                 b= c(-1,-10,-2,0,0,2,1,4,10,12,6, "apple", "apple", "Orange"))
df 
    a      b
1   1     -1
2   2    -10
3   3     -2
4   4      0
5   5      0
6   6      2
7   7      1
8   8      4
9   9     10
10 10     12
11 11      6
12 12  apple
13 13  apple
14 14 Orange


df2
    a      b      c
1   1     -1     <0
2   2    -10     <0
3   3     -2     <0
4   4      0      0
5   5      0      0
6   6      2    0-3
7   7      1    0-3
8   8      4     >3
9   9     10     >3
10 10     12     >3
11 11      6     >3
12 12  apple  apple
13 13  apple  apple
14 14 Orange Orange

我正在嘗試應用case_whencut 我得到了我需要的結果。 我將不勝感激任何幫助和提示。

df %>%
mutate(c = case_when( b %in% grepl("apple|orange", b) ~ b),
                      TRUE ~ cut(as.numeric(b),
                                                       breaks = c(-999, 0, 1, 4, 999),
                                                       labels = c("<0", "0", "0-3", ">3"),
                                                       right = F)) 

將數字從非數字中分離出來並單獨進行可能會更好。 base R中,我們可以對每個子集進行兩次賦值

i1 <- grepl("^-?[0-9]+$", df$b)
df$c[i1] <- as.character(cut(as.numeric(df$b[i1]), 
   breaks = c(-999, 0, 1, 4, 999), labels = c("<0", "0", "0-3", ">3"), right = FALSE))
df$c[!i1] <- df$b[!i1]

-輸出

> df
    a      b      c
1   1     -1     <0
2   2    -10     <0
3   3     -2     <0
4   4      0      0
5   5      0      0
6   6      2    0-3
7   7      1    0-3
8   8      4     >3
9   9     10     >3
10 10     12     >3
11 11      6     >3
12 12  apple  apple
13 13  apple  apple
14 14 Orange Orange

如果我們想使用dplyr

library(dplyr)
df %>%
mutate(c = coalesce(case_when( !grepl("apple|orange", b)  ~ as.character(cut(as.numeric(b),
                                                       breaks = c(-999, 0, 1, 4, 999),
                                                       labels = c("<0", "0", "0-3", ">3"),
                                                       right = FALSE))), b))

-輸出

  a      b      c
1   1     -1     <0
2   2    -10     <0
3   3     -2     <0
4   4      0      0
5   5      0      0
6   6      2    0-3
7   7      1    0-3
8   8      4     >3
9   9     10     >3
10 10     12     >3
11 11      6     >3
12 12  apple  apple
13 13  apple  apple
14 14 Orange Orange

注意: case_whenifelse將 function 應用於整個數據,因此當我們執行as.numeric時,非數字元素被強制轉換為NA ,因此第一個選項被覆蓋。 相反,在case_when之后使用replacecoalesce with b column

暫無
暫無

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

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