R语言 有条件地将因子变量1的水平替换为特定变量2

aurhwmvo  于 2023-01-10  发布在  其他
关注(0)|答案(3)|浏览(140)

在我的例子中:

# Packages
library(dplyr)

# My dataset
FARM <- c(rep("LIBERTY2",4),rep("OLDOAK",4))
AGE <- c(8,9,10,10,8,9,10,10)
Y = c(0,0,0,0,1,1,1,1)
DS_F <- data.frame(FARM=FARM,AGE=AGE,Y=Y)
str(DS_F)
# 'data.frame': 8 obs. of  3 variables:
#  $ FARM: chr  "LIBERTY2" "LIBERTY2" "LIBERTY2" "LIBERTY2" ...
#  $ AGE : num  8 9 10 10 8 9 10 10
#  $ Y   : num  0 0 0 0 1 1 1 1

我想在变量FARM中只对LIBERTY2因子进行条件变异,并在另一个变量中使用规则:如果AGE等于10则小于3,如果AGE等于9则小于2,如果AGE等于8则小于1。

My final output should be:
DS_F2
#       FARM AGE Y
# 1 LIBERTY2   1 0
# 2 LIBERTY2   2 0
# 3 LIBERTY2   3 0
# 4 LIBERTY2   3 0
# 5   OLDOAK   8 1
# 6   OLDOAK   9 1
# 7   OLDOAK  10 1
# 8   OLDOAK  10 1

拜托,帮帮我。

l0oc07j2

l0oc07j21#

您可以将recode()包围成if_else()

library(dplyr)

DS_F %>%
  mutate(AGE.2 = if_else(FARM == "LIBERTY2",
                         recode(AGE, `10` = 3, `9` = 2, `8` = 1),
                         AGE))

#       FARM AGE Y AGE.2
# 1 LIBERTY2   8 0     1
# 2 LIBERTY2   9 0     2
# 3 LIBERTY2  10 0     3
# 4 LIBERTY2  10 0     3
# 5   OLDOAK   8 1     8
# 6   OLDOAK   9 1     9
# 7   OLDOAK  10 1    10
# 8   OLDOAK  10 1    10
s2j5cfk0

s2j5cfk02#

这是你要找的吗?

DS_F <- DS_F %>%
  mutate(FARM = as.factor(FARM),
         RULE = case_when(AGE == 10 ~ 3, 
                          AGE == 9 ~ 2,
                          AGE == 8 ~ 1))

其产生

> DS_F %>%
+   mutate(FARM = as.factor(FARM),
+          RULE = case_when(AGE == 10 ~ 3, 
+                           AGE == 9 ~ 2,
+                           AGE == 8 ~ 1))
      FARM AGE Y RULE
1 LIBERTY2   8 0    1
2 LIBERTY2   9 0    2
3 LIBERTY2  10 0    3
4 LIBERTY2  10 0    3
5   OLDOAK   8 1    1
6   OLDOAK   9 1    2
7   OLDOAK  10 1    3
8   OLDOAK  10 1    3

具有以下数据类型

> str(DS_F)
'data.frame':   8 obs. of  4 variables:
 $ FARM: Factor w/ 2 levels "LIBERTY2","OLDOAK": 1 1 1 1 2 2 2 2
 $ AGE : num  8 9 10 10 8 9 10 10
 $ Y   : num  0 0 0 0 1 1 1 1
 $ RULE: num  1 2 3 3 1 2 3 3
egdjgwm8

egdjgwm83#

使用data.table

library(data.table)
setDT(DS_F)[FARM == "LIBERTY2", AGE := AGE - min(AGE)+1]
  • 输出
> DS_F
       FARM AGE Y
1: LIBERTY2   1 0
2: LIBERTY2   2 0
3: LIBERTY2   3 0
4: LIBERTY2   3 0
5:   OLDOAK   8 1
6:   OLDOAK   9 1
7:   OLDOAK  10 1
8:   OLDOAK  10 1

相关问题