How to sort data into new columns based on information in other columns

Viewed 52

I have data on fiddler crabs that includes which of its claws are dominate (L or R) (listed as handedness), and the length of specific walking legs (the merus) on each side, which are again sorted by L and R.

Merus_L Merus_R Handedness
13.300 10.950 R
9.980 12.250 L
8.750 12.150 L

What I want is to have a column (or a way) to sort these merus values by whether they were on the same side as the major claw (aka dominate claw). for example, if you go back to the above table, the first crab is right handed, so I would like the Merus_R data to be listed under a column called "Major_merus", and the data from Merus_L to be listed under "Minor_merus". the correct sorting is shown below:

Major_merus Minor_merus Handedness
10.950 13.300 R
9.980 12.250 L
8.750 12.150 L

I've already tried the ifelse command recommended by my professor, but I don't know how to use the new data, or why only the Major_merus is correct now.

Morphdata$Major_merus<-ifelse(Morphdata$Handedness=="L","Merus_L","Merus_R")
Morphdata$Minor_merus<-ifelse(Morphdata$Handedness=="R","Merus_R","Merus_L")
Major_merus Minor_merus
Merus_R Merus_R
Merus_L Merus_L
Merus_L Merus_L

Sorry if this formatting is incorrect, it's my first post!

1 Answers

I modified the solution, I guess this one is more straight forward:

  • For Major_mercus column, I first created a customized name with paste0 by concatenating Merus_ with the value of Handedness in every row. Then I retrieve the value with get function
  • For Minor_mercus I basically did the same but I used ifelse to first swap the R and L value in each row and then retrieve the desired value
library(dplyr)

df %>%
  rowwise() %>%
  mutate(Major_mercus = get(paste0("Merus_", Handedness)),
         Minor_mercus = get(paste0("Merus_", ifelse(Handedness == "R", "L", "R")))) %>%
  select(ends_with("mercus"), Handedness)

# A tibble: 3 x 3
# Rowwise: 
  Major_mercus Minor_mercus Handedness
         <dbl>        <dbl> <chr>     
1        11.0          13.3 R         
2         9.98         12.2 L         
3         8.75         12.2 L 
Related