I have a column that looks like this
value
Ford
2,300
Chevy
15
Toyota
245
And I want to transform it and I'm looking for something like this
Brand Value
Ford 2,300
Chevy 15
Toyota 245
What's the best way to get here using a tidyvere solution?
CodePudding user response:
If these are alternate elements, easier option is to use a recycling logical vector to extract in base R
data.frame(Brand = df1$value[c(TRUE, FALSE)], Value = df1$value[c(FALSE, TRUE)])
Brand Value
1 Ford 2,300
2 Chevy 15
3 Toyota 245
data
df1 <- structure(list(value = c("Ford", "2,300", "Chevy", "15", "Toyota",
"245")), class = "data.frame", row.names = c(NA, -6L))
CodePudding user response:
You can also use dplyr::summarize() with @akrun's simple solution.
library(dplyr)
summarize(df1, Brand = value[c(T, F)], value = value[c(F, T)])
#> Brand value
#> 1 Ford 2,300
#> 2 Chevy 15
#> 3 Toyota 245
CodePudding user response:
We could use lag() and filter out:
library(dplyr)
df1 %>%
mutate(Brand = lag(value)) %>%
filter(row_number() %% 2 == 0) %>%
select(Brand, Value=value)
Brand Value
1 Ford 2,300
2 Chevy 15
3 Toyota 245
CodePudding user response:
Yet another solution:
library(tidyverse)
df <- data.frame(
stringsAsFactors = FALSE,
value = c("Ford", "2300", "Chevy", "15", "Toyota", "245")
)
filter(df, row_number() %% 2 == 1) %>%
{bind_cols(set_names(.,"brand"), filter(df, row_number() %% 2 == 0))}
#> brand value
#> 1 Ford 2300
#> 2 Chevy 15
#> 3 Toyota 245
