我认为这是一个非常直接的重塑,尽管我们正在努力。我们有这个数据框:
structure(list(X1 = c("Title:", "Phone:", "Email:", "Previous College:"
), X2 = c("Head Coach, Year2", "123-456-7890", "[email protected]",
"The Best")), class = "data.frame", row.names = c(NA,
-4L))
X1 X2
1 Title: Head Coach, Year2
2 Phone: 123-456-7890
3 Email: [email protected]
4 Previous College: The Best
我们正在尝试将其转换为像这样的 1 行数据帧:
data.frame(Title = 'Head Coach, Year2', Phone = '123-456-7890', Email = '[email protected]', `Previous College` = 'The Best', stringsAsFactors = FALSE)
Title Phone Email Previous.College
1 Head Coach, Year2 123-456-7890 [email protected] The Best
我们可以deframe
并转换为 tibble
library(dplyr)
library(stringr)
library(tibble)
df1 %>%
mutate(X1 = str_remove(X1, ":")) %>%
deframe %>%
as_tibble_row
# A tibble: 1 x 4
Title Phone Email `Previous College`
<chr> <chr> <chr> <chr>
1 Head Coach, Year2 123-456-7890 [email protected] The Best
或base R
通过使用 'X1' 列设置名称并使用as.data.frame.list
将命名转换为vector
data.frame
as.data.frame.list(with(df1, setNames(X2, trimws(X1,
whitespace = ":"))), check.names = FALSE)
Title Phone Email Previous College
1 Head Coach, Year2 123-456-7890 [email protected] The Best
或与 data.table::transpose
data.table::transpose(df1, make.names = 'X1')
Title: Phone: Email: Previous College:
1 Head Coach, Year2 123-456-7890 [email protected] The Best
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句