data.table의 plyr :: mapvalues의 대안

DJV

나는에 읽을 수있는 대안을 찾고 plyr::mapvalues에서 data.table.

예를 들어,에 plyr::mapvalues, 나는의 값을 변경하려는 경우 carbmtcarstype1, type2, type3, 내가 이런 짓을 할 것이다 :

library(tidyverse)

mtcars %>% 
  mutate(carb = plyr::mapvalues(
    carb,
    from = c("1", "2", "3", "4", "6", "8"),
    to = c("type1", "type1", "type2", "type2", "type3", "type3")))

에서 동일한 것을 얻으려면 다음과 data.table같이 수행합니다. 이는 기존의 방법이 아닌 것 같습니다.

library(data.table)

dt <- data.table(mtcars)
dt$carb <- as.character(dt$carb)

dt[which(carb %in% c("1", "2")), 
   carb := "type1"]

dt[which(carb %in% c("3", "4")), 
   carb := "type2"]

dt[which(carb %in% c("6", "8")), 
   carb := "type3"]

하나의 조건 ( dt[...]) 에서 모든 값을 변경할 수 있습니까?

미디엄--

사용하는 base::factor것이 가장 쉬운 방법입니다.

library(data.table)

setDT(mtcars)[, carb := factor(carb, 
                                levels = c("1", "2", "3", 
                                           "4", "6", "8"),
                                labels = c("type1", "type1",
                                           "type2", "type2", 
                                           "type3", "type3"))][]

#>      mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#>  1: 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4 type2
#>  2: 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4 type2
#>  3: 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4 type1
#>  4: 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3 type1
#>  5: 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3 type1
#>  6: 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3 type1
#>  7: 14.3   8 360.0 245 3.21 3.570 15.84  0  0    3 type2
#>  8: 24.4   4 146.7  62 3.69 3.190 20.00  1  0    4 type1
#>  9: 22.8   4 140.8  95 3.92 3.150 22.90  1  0    4 type1
## ...

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사