R Programming - Create a Factor Corresponding to Women’s Height and weights Data
R Programming: Factors Exercise-7 with Solution
Write a R program to create a factor corresponding to height of women data set, which contains height and weights for a sample of women.
Sample Solution :
R Programming Code :
# Load the built-in 'women' dataset, which contains height and weight data
data = women
# Print a message indicating that the women data set will be displayed
print("Women data set of height and weights:")
# Print the 'women' dataset
print(data)
# Create a factor by dividing the 'height' variable into 3 intervals
height_f = cut(women$height, 3)
# Print a message indicating that the factor corresponding to height will be displayed
print("Factor corresponding to height:")
# Print the frequency table of the height factor
print(table(height_f))
Output:
[1] "Women data set of height and weights:" height weight 1 58 115 2 59 117 3 60 120 4 61 123 5 62 126 6 63 129 7 64 132 8 65 135 9 66 139 10 67 142 11 68 146 12 69 150 13 70 154 14 71 159 15 72 164 [1] "Factor corresponding to height:" height_f (58,62.7] (62.7,67.3] (67.3,72] 5 5 5
Explanation:
- data = women
- Purpose: Loads the built-in women dataset, which includes height and weight measurements for a sample of women, and assigns it to the variable data.
- print("Women data set of height and weights:")
- Purpose: Prints a message to indicate that the next output will be the data set showing the heights and weights of women.
- print(data)
- Purpose: Displays the women dataset, showing the height and weight of each sample.
- height_f = cut(women$height, 3)
- Purpose: Creates a factor variable height_f by dividing the height column of the women dataset into 3 intervals (bins). The cut function categorizes the heights into these intervals.
- print("Factor corresponding to height:")
- Purpose: Prints a message to indicate that the next output will be the factor levels corresponding to the height data.
- print(table(height_f))
- Purpose: Displays a frequency table of the height_f factor, showing how many women fall into each of the 3 height intervals.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/r-programming-exercises/factors/r-programming-factors-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics