简体   繁体   English

R中的mutate_at函数

[英]function mutate_at in R

I would like to achieve the output as follow table. 我想实现输出如下表。

Could anyone help with the above codes? 有人可以帮忙上面的代码吗? The task is mainly about how to insert a new column by using function. 任务主要是关于如何使用函数插入新列。 But I am not sure if I have to use mutate_at. 但是我不确定是否必须使用mutate_at。 The error came with length > 1 , I have no clues about this. 错误的长度大于1,我对此一无所知。

Thanks!!! 谢谢!!!

## I would like to achieve the output as follow
## A B C best
## 1 2 4 Par
## 2 3 1 Lab
## 3 4 9 Par
## 4 1 0 Edu

## I tried the following codes, however, it didnt work
Library("dplyr")
Library("tidyr")
   data <- data.frame(A = c(1,2,3,4),
                       B = c(2,3,4,1),
                       C = c(4,1,9,0))

best <- function(x,y,z){
         if ((x>y)&(x>z)){
         print("Edu")
         if ((y>x)&(y>z))
         print("Lab")
         if ((z>x)&(z>y))
         print("Par")
         }
    }

data_new <- mutate_at(data, vars(A:C), funs(best))

May I ask how can I solve this 请问我该如何解决

How about 怎么样

data_new <- data %>%
    mutate(
        best = case_when(
            A>B & A>C ~ "Edu",
            B>A & B>C ~ "Lab",
            C>A & C>B ~ "Par",
            TRUE ~ NA_character_
        )
   )

Or is it important for you to work independent of column names? 还是独立于列名对您来说重要吗?

best <- function(x,y,z){
  if ((x>y)&(x>z)){
    "Edu" } else if ((y>x)&(y>z)){
    "Lab" } else if ((z>x)&(z>y)){
    "Par"
    }
}
library(dplyr)
data %>% rowwise() %>% mutate(best=best(A,B,C))

I don't think you can use mutate_at in your case see ?mutate_at . 我认为您无法在自己的情况下使用mutate_at ,请参阅?mutate_at We need rowwise() as best isn't vectorise function. 我们best rowwise()因为best不是rowwise()函数。

Rowwise can be avoided by using pmap. 通过使用pmap可以避免按行。

best <- function(x,y,z) {
  case_when( x > y & x > z ~ "Edu",
             y > x & y > z ~ "Lab",
             z > x & z > y ~ "Par",
             TRUE ~ NA_character_)
}

data %>% bind_cols(best_col = pmap_chr(unname(.),best))

  A B C best_col
1 1 2 4      Par
2 2 3 1      Lab
3 3 4 9      Par
4 4 1 0      Edu

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM