I would like to use the first value of a helper-column, which contains the same string in each row, as the column name for the column which has the actual values. The dfs are stored in a list. Is there a way to handle this with purrr
? (I have tried but did not find a solution)
Example:
# Create dataframe
df1 = data.frame(
A = c(1, 2, 3),
B = c("df1", "df1", "df1")
)
# Create another dataframe
df2 = data.frame(
A = c(4, 5, 6),
B = c("df2", "df2", "df2")
)
# Create list of data frames
list1 = list(df1, df2)
And this is how i would like the dfs to look like within the list:
[[1]]
df1
1 1
2 2
3 3
[[2]]
df2
1 4
2 5
3 6
I really appreciate any ideas and solutions, thanks!!
I have tried with plucking the first value that contains the string but I can't think of a solution that allows me to map the values as new column names to the list.
I would go for Tim's solution if possible, however, if your dataframes are named differently than the B column you could do
first_data = data.frame(
A = c(1, 2, 3),
B = c("df1", "df1", "df1")
)
# Create another dataframe
second_data = data.frame(
A = c(4, 5, 6),
B = c("df2", "df2", "df2")
)
library(purrr)
library(dplyr)
list(first_data,second_data) |>
set_names(c((first_data$B[1]), second_data$B[1])) |>
map(~.x |> select(-B))
$df1
A
1 1
2 2
3 3
$df2
A
1 4
2 5
3 6