R语言新手求助:如何生成含各列最大值对应Food的vector
Hey there! Let's break this down into simple, actionable steps. First, let's make sure we have your data loaded into an R data frame correctly:
# Create the data frame food_df <- data.frame( Food = c("Apple", "Apricot", "Avocado", "Blueberry", "Blackberry"), energy = c(207, 153, 523, 204, 170), water = c(84, 87, 81, 80, 85), fiber = c(2.3, 2.1, 0.2, 8.4, 8.7), stringsAsFactors = FALSE )
Now, here are two solid approaches to get your desired Food vector—one using base R (great for learning core concepts) and another using the tidyverse (cleaner for data manipulation tasks).
Base R Approach
We can use sapply() to iterate over the columns we care about, find the row index where the maximum value occurs, then pull the corresponding Food name:
# Define the columns we want to check target_cols <- c("energy", "water", "fiber") # Extract Food names for each column's maximum max_foods <- sapply(target_cols, function(col) { food_df$Food[which.max(food_df[[col]])] }) # Convert to a plain vector (optional, since sapply returns a named vector) max_foods_vector <- unname(max_foods) # View the result max_foods_vector # Output: "Avocado" "Apricot" "Blackberry"
How this works:
which.max()finds the first occurrence of the maximum value in a column (perfect here since all maxima are unique).sapply()applies our function to each column intarget_cols, returning a named vector. We useunname()if we want an unnamed vector.
Tidyverse Approach
If you're open to using the dplyr and tidyr packages (super popular for data wrangling), this method is more readable for complex tasks:
First, install and load the packages if you haven't already:
install.packages("tidyverse") library(tidyverse)
Then:
max_foods_tidy <- food_df %>% # Convert wide data to long format (easier to group by nutrient) pivot_longer(cols = -Food, names_to = "nutrient", values_to = "value") %>% # Group by each nutrient group_by(nutrient) %>% # Keep only the row with the maximum value for each nutrient filter(value == max(value)) %>% # Extract just the Food names as a vector pull(Food) # View the result max_foods_tidy # Output: "Avocado" "Apricot" "Blackberry"
How this works:
pivot_longer()reshapes the data so each row is a Food-nutrient-value combination.group_by(nutrient)lets us handle each nutrient separately.filter(value == max(value))keeps only the row where the value is the maximum for that nutrient.pull(Food)extracts the Food column into a vector.
Both methods will give you exactly the vector you need. For a beginner, starting with the base R approach can help you build a strong foundation, while the tidyverse approach is great to learn as you tackle more complex data tasks!
内容的提问来源于stack exchange,提问作者Rajendra Warke

