This is an example of how to use the `pivot_longer` function in R to exclude multiple columns.
Consider the following data frame:
“`R
# Original Data Frame
df <- data.frame(
ID = 1:3,
Name = c("John", "Jane", "Michael"),
Age = c(25, 30, 35),
Salary = c(50000, 60000, 70000),
Department = c("HR", "Finance", "IT")
)
```
Using the `pivot_longer` function from the `tidyverse` package, you can exclude multiple columns while reshaping your data.
Here's an example of how to use `pivot_longer` to exclude the columns 'Name' and 'Department':
```R
# Exclude 'Name' and 'Department' columns
df_long <- df %>%
pivot_longer(
cols = -c(Name, Department),
names_to = “Variable”,
values_to = “Value”
)
“`
In this example, the `cols` argument in `pivot_longer` specifies the columns that should be excluded. By using the `-` sign before the columns you want to exclude, you can retain all other columns.
The `names_to` argument specifies the name of the new column that will contain the original column names, and the `values_to` argument specifies the name of the new column that will contain the values from the original columns.
The resulting data frame `df_long` will look like this:
“`R
# Resulting Data Frame
ID Variable Value
1 1 Age 25
2 1 Salary 50000
3 2 Age 30
4 2 Salary 60000
5 3 Age 35
6 3 Salary 70000
“`
As you can see, the `pivot_longer` function transformed the original data frame from a wide format to a long format, excluding the ‘Name’ and ‘Department’ columns.
Note: `df_long` contains four columns: ‘ID’ (the primary identifier), ‘Variable’ (the original column names), and ‘Value’ (the values from the original columns).
- Padding is invalid and cannot be removed
- Pandas float division by zero
- Pandas bar plot sort x axis
- Python strptime multiple formats
- Pandas reverse one hot encoding
- Pydantic json exclude
- Display nested JSON data in HTML table using JavaScript dynamically
- Pivot table error this command requires at least two rows of source data