在R中使用字符时mutate()错误

时间:2019-04-02 15:53:26

标签: r mutate

我正在使用如下所示的数据集:

test_accuracy <- data.frame(observed = c("Feeding/Moving", "Moving/Feeding", 
"Moving/Feeding", "Moving/Feeding", "Feeding/Moving", "Feeding/Moving"),
                            predicted = c("Standing", "Standing", 
"Standing", "Standing", "Standing", "Moving/Feeding"))

我正在尝试通过替换列predicted中的某些字符来转换数据,例如:

1)将Feeding/Moving替换为Standing

2)将Standing替换为Moving/Feeding

3)将Moving/Feeding替换为Feeding/Moving

我尝试使用下面的代码以紧凑的方式应用此转换,并出现以下错误:

> test_accuracy<-test_accuracy %>%
+ mutate(predicted = case_when(predicted == 'Feeding/Moving' ~ 'Standing',
+                                predicted == 'Standing' ~ 'Moving/Feeding',
+                                predicted == 'Moving/Feeding' ~ 'Feeding/Moving',
+                                TRUE ~ predicted)) %>%
+ 
+ 
+ head(test_accuracy)
Error in mutate_impl(.data, dots) : 
  Evaluation error: must be type character, not integer
Call `rlang::last_error()` to see a backtrace.

但是,当尝试通过将类型设置为character进行纠正时,我得到了相反的错误消息:

> test_accuracy<-as.character(test_accuracy)
> test_accuracy<-test_accuracy %>%
+ mutate(predicted = case_when(predicted == 'Feeding/Moving' ~ 'Standing',
+                                predicted == 'Standing' ~ 'Moving/Feeding',
+                                predicted == 'Moving/Feeding' ~ 'Feeding/Moving',
+                                TRUE ~ predicted)) %>%
+ 
+ 
+ head(test_accuracy)
Error in UseMethod("mutate_") : 
  no applicable method for 'mutate_' applied to an object of class "character"

关于如何使用此数据集实现上述所需转换的任何想法?任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

当我遇到一些类别的此类问题时,我使用嵌套的ifelse()函数将其合并到mutate()函数中。我的建议如下:

df <- data.frame(observed = c("Feeding/Moving", "Moving/Feeding", 
"Moving/Feeding", "Moving/Feeding", "Feeding/Moving", "Feeding/Moving"),
                 predicted = c("Standing", "Standing", "Standing", "Standing", 
"Standing", "Moving/Feeding"))

new_df <- df %>% 
  mutate(new_observed = ifelse(observed == "Standing", "Moving/Feeding", 
         ifelse(observed == "Moving/Feeding", "Feeding/Moving", "Standing")),
         new_predicted = ifelse(predicted == "Standing", "Moving/Feeding", 
         ifelse(predicted == "Moving/Feeding", "Feeding/Moving", "Standing")))

请注意,如果第一个条件不是ifelse(),则将第二个ifelse()函数作为第一个True函数的第三个参数来放置新条件。结果输出如下(如果我误解了上面的替换规则,请原谅我):

> new_df
        observed      predicted   new_observed  new_predicted
1 Feeding/Moving       Standing       Standing Moving/Feeding
2 Moving/Feeding       Standing Feeding/Moving Moving/Feeding
3 Moving/Feeding       Standing Feeding/Moving Moving/Feeding
4 Moving/Feeding       Standing Feeding/Moving Moving/Feeding
5 Feeding/Moving       Standing       Standing Moving/Feeding
6 Feeding/Moving Moving/Feeding       Standing Feeding/Moving