[英]How to convert two vectors into dataframe (wide format)
I want to convert two vectors into a wide format dataframe. The fist vector represent the column names and the second vector the values.我想将两个向量转换为宽格式 dataframe。第一个向量代表列名,第二个向量代表值。 Here is my reproduceable example:
这是我的可重现示例:
vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)
Now I want to convert these two vector into a wide format dataframe:现在我想将这两个向量转换成宽格式 dataframe:
# A tibble: 1 x 5
Reply Reshare Like Share Search
<dbl> <dbl> <dbl> <dbl> <dbl>
1 2 1 0 4 3
I have found some examples for the long format, but none simple solution for the wide format.我找到了一些长格式的示例,但没有找到宽格式的简单解决方案。 Can anyone help me?
谁能帮我?
You can make a named list (eg using setNames
), followed by as.data.frame
:您可以制作一个命名列表(例如使用
setNames
),然后是as.data.frame
:
df <- as.data.frame(setNames(as.list(vector2), vector1))
Note that it needs to be a list: when converting a named vector into a data.frame
, R puts values into separate rows instead of columns.请注意,它必须是一个列表:将命名向量转换为
data.frame
时,R 会将值放入单独的行而不是列中。
vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)
df <- data.frame(vector1, vector2)
df |> tidyr::pivot_wider(names_from = vector1, values_from = vector2)
#> # A tibble: 1 × 5
#> Reply Reshare Like Share Search
#> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 2 1 0 4 3
Created on 2022-02-08 by the reprex package (v2.0.1)由reprex package (v2.0.1) 创建于 2022-02-08
Yet another solution, based on dplyr::bind_rows
:另一种解决方案,基于
dplyr::bind_rows
:
library(dplyr)
vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)
names(vector2) <- vector1
bind_rows(vector2)
#> # A tibble: 1 × 5
#> Reply Reshare Like Share Search
#> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 2 1 0 4 3
We can use map_dfc
and set_names
我们可以使用
map_dfc
和set_names
library(purrr)
set_names(map_dfc(vector2, ~.x), vector1)
# A tibble: 1 × 5
Reply Reshare Like Share Search
<dbl> <dbl> <dbl> <dbl> <dbl>
1 2 1 0 4 3
Another possible solution:另一种可能的解决方案:
library(dplyr)
data.frame(rbind(vector1, vector2)) %>%
`colnames<-`(.[1, ]) %>%
.[-1, ] %>%
`rownames<-`(NULL)
Reply Reshare Like Share Search
1 2 1 0 4 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.