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. The error came with length > 1 , I have no clues about this.
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
. We need rowwise()
as best
isn't vectorise function.
Rowwise can be avoided by using 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.