Error while using the forcats relevel function

314 Views Asked by At

I have a dataframe with X, Y coordinate values and corresponding ID values in Val.

df1 <- data.frame(X=rnorm(1000,0,1), Y=rnorm(1000,0,1), 
                 ID=paste(rep("ID", 1000), 1:1000, sep="_"),
                 Type=rep("ID",1000),
                 Val=c(rep(c('Type1','Type2'),300),
                       rep(c('Type3','Type4'),200)))

Adding the missing IDs for the existing X,Y values in df1.

dat2 <- data.frame(Type=rep('D',8),
                   Val=paste(rep("D", 8), 
                             sample(1:2,8,replace=T), sep="_"))
dat2 <- cbind(df[sample(1:1000,80),1:3],dat2)

df1 <- rbind(df1, dat2)

Looking at the frequency of ID values.

df1 %>% count(Val)

# # A tibble: 6 x 2
#      Val     n
#   <fctr> <int>
# 1  Type1   300
# 2  Type2   300
# 3  Type3   200
# 4  Type4   200
# 5    D_1    60
# 6    D_2    20

I am interested in only two IDs for further analysis and the rest can be grouped into a random value. With the help of fct_other function, I have recoded them into Other and the frequency looks as expected.

df1 %>% mutate(Val=fct_other(Val,keep=c('D_1','D_2'))) %>% count(Val)

# # A tibble: 3 x 2
#      Val     n
#   <fctr> <int>
# 1    D_1    60
# 2    D_2    20
# 3  Other  1000

As the fct_other function puts "Other" values as the last factor value and I want it at first, I used the other function fct_relevel available in the same package.

df1 %>% mutate(Val=fct_other(Val,keep=c('Type5','Type6'))) %>% 
  mutate(Val=fct_relevel(Val,'Other'))%>% 
  count(Val)

# # A tibble: 1 x 2
#      Val     n
#   <fctr> <int>
# 1  Other  1080

But it is giving unexpected results. Any idea on what might have gone wrong?

Update: The error was trying to keep unavailable values.

df1 %>% mutate(Val=fct_other(Val,keep=c('D_1','D_2'))) %>% 
  mutate(Val=fct_relevel(Val,'Other'))%>% count(Val)

# # A tibble: 3 x 2
#      Val     n
#   <fctr> <int>
# 1  Other  1000
# 2    D_1    30
# 3    D_2    50

When I tried to retain the unique values, the selected ones are missing:

df1 %>% mutate(Val=fct_other(Val,keep=c('D_1','D_2'))) %>% 
  mutate(Val=fct_relevel(Val,'Other'))%>% 
  arrange(Val) %>% filter(!duplicated(.[,c("X","Y")])) %>% count(Val)

# # A tibble: 1 x 2
#       Val     n
#     <fctr> <int>
#   1  Other  1000

Relevelling after the extraction of unique values does the job:

df1 %>% mutate(Val=fct_other(Val,keep=c('D_1','D_2'))) %>% 
  arrange(Val) %>% filter(!duplicated(.[,c("X","Y")])) %>% 
  mutate(Val=fct_relevel(Val,'Other'))  %>% 
  arrange(Val) %>% count(Val)
# # A tibble: 3 x 2
#      Val     n
#   <fctr> <int>
# 1  Other   920
# 2    D_1    30
# 3    D_2    50

Is this the efficient way of doing it?

0

There are 0 best solutions below